From 34bc9bdefb3072e7c3ff03104ce0ebd7e9536121 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 14 Nov 2022 19:16:48 +0800 Subject: [PATCH 01/50] ibc: init ibc module --- bsc/rate.go | 31 ++ proto/cosmos/ibc/v1/event.proto | 18 + proto/cosmos/ibc/v1/ibc.proto | 13 + proto/cosmos/ibc/v1/query.proto | 56 +++ types/cross_chain.go | 101 ++++++ x/ibc/README.md | 6 + x/ibc/keeper/config.go | 26 ++ x/ibc/keeper/keeper.go | 205 +++++++++++ x/ibc/keeper/querier.go | 19 ++ x/ibc/module.go | 135 ++++++++ x/ibc/types/event.pb.go | 589 ++++++++++++++++++++++++++++++++ x/ibc/types/expected_keepers.go | 10 + x/ibc/types/ibc.pb.go | 303 ++++++++++++++++ x/ibc/types/keys.go | 93 +++++ x/ibc/types/params.go | 45 +++ 15 files changed, 1650 insertions(+) create mode 100644 bsc/rate.go create mode 100644 proto/cosmos/ibc/v1/event.proto create mode 100644 proto/cosmos/ibc/v1/ibc.proto create mode 100644 proto/cosmos/ibc/v1/query.proto create mode 100644 types/cross_chain.go create mode 100644 x/ibc/README.md create mode 100644 x/ibc/keeper/config.go create mode 100644 x/ibc/keeper/keeper.go create mode 100644 x/ibc/keeper/querier.go create mode 100644 x/ibc/module.go create mode 100644 x/ibc/types/event.pb.go create mode 100644 x/ibc/types/expected_keepers.go create mode 100644 x/ibc/types/ibc.pb.go create mode 100644 x/ibc/types/keys.go create mode 100644 x/ibc/types/params.go diff --git a/bsc/rate.go b/bsc/rate.go new file mode 100644 index 0000000000..bdab0343d4 --- /dev/null +++ b/bsc/rate.go @@ -0,0 +1,31 @@ +package bsc + +import ( + "math" + "math/big" +) + +const ( + BNBDecimalOnBFS = 8 + BNBDecimalOnBSC = 18 +) + +func GetBigIntForDecimal(decimal int) *big.Int { + floatDecimal := big.NewFloat(math.Pow10(decimal)) + bigIntDecimal := new(big.Int) + floatDecimal.Int(bigIntDecimal) + + return bigIntDecimal +} + +// ConvertBCAmountToBSCAmount can only be used to convert BNB decimal +func ConvertBCAmountToBSCAmount(bcAmount int64) *big.Int { + decimals := GetBigIntForDecimal(BNBDecimalOnBSC - BNBDecimalOnBFS) + return big.NewInt(0).Mul(big.NewInt(bcAmount), decimals) +} + +// ConvertBSCAmountToBCAmount can only be used to convert BNB decimal +func ConvertBSCAmountToBCAmount(bscAmount *big.Int) int64 { + decimals := GetBigIntForDecimal(BNBDecimalOnBSC - BNBDecimalOnBFS) + return big.NewInt(0).Div(bscAmount, decimals).Int64() +} diff --git a/proto/cosmos/ibc/v1/event.proto b/proto/cosmos/ibc/v1/event.proto new file mode 100644 index 0000000000..cdd6fcf2bc --- /dev/null +++ b/proto/cosmos/ibc/v1/event.proto @@ -0,0 +1,18 @@ +// Since: cosmos-sdk 0.43 +syntax = "proto3"; +package cosmos.authz.v1beta1; + +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; + +message EventIBCPackage { + uint32 src_chain_id = 1; + uint32 dest_chain_id = 2; + uint32 channel_id = 3; + uint64 sequence = 4; + uint32 package_type = 5; + uint64 timestamp = 6; + bytes package_load = 7; + string relayer_fee = 8; +} diff --git a/proto/cosmos/ibc/v1/ibc.proto b/proto/cosmos/ibc/v1/ibc.proto new file mode 100644 index 0000000000..2b9c512e76 --- /dev/null +++ b/proto/cosmos/ibc/v1/ibc.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package cosmos.ibc.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +// Params holds parameters for the mint module. +message Params { + uint64 relayer_fee = 1; +} + diff --git a/proto/cosmos/ibc/v1/query.proto b/proto/cosmos/ibc/v1/query.proto new file mode 100644 index 0000000000..b7e7553b3e --- /dev/null +++ b/proto/cosmos/ibc/v1/query.proto @@ -0,0 +1,56 @@ +syntax = "proto3"; +package cosmos.mint.v1beta1; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; + +// Query provides defines the gRPC querier service. +service Query { + // Params returns the total set of minting parameters. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/cosmos/mint/v1beta1/params"; + } + + // Inflation returns the current minting inflation value. + rpc Inflation(QueryInflationRequest) returns (QueryInflationResponse) { + option (google.api.http).get = "/cosmos/mint/v1beta1/inflation"; + } + + // AnnualProvisions current minting annual provisions value. + rpc AnnualProvisions(QueryAnnualProvisionsRequest) returns (QueryAnnualProvisionsResponse) { + option (google.api.http).get = "/cosmos/mint/v1beta1/annual_provisions"; + } +} + +// QueryParamsRequest is the request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is the response type for the Query/Params RPC method. +message QueryParamsResponse { + // params defines the parameters of the module. + Params params = 1 [(gogoproto.nullable) = false]; +} + +// QueryInflationRequest is the request type for the Query/Inflation RPC method. +message QueryInflationRequest {} + +// QueryInflationResponse is the response type for the Query/Inflation RPC +// method. +message QueryInflationResponse { + // inflation is the current minting inflation value. + bytes inflation = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; +} + +// QueryAnnualProvisionsRequest is the request type for the +// Query/AnnualProvisions RPC method. +message QueryAnnualProvisionsRequest {} + +// QueryAnnualProvisionsResponse is the response type for the +// Query/AnnualProvisions RPC method. +message QueryAnnualProvisionsResponse { + // annual_provisions is the current minting annual provisions value. + bytes annual_provisions = 1 + [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; +} diff --git a/types/cross_chain.go b/types/cross_chain.go new file mode 100644 index 0000000000..582071ef37 --- /dev/null +++ b/types/cross_chain.go @@ -0,0 +1,101 @@ +package types + +import ( + "encoding/binary" + "fmt" + "math" + "math/big" + "strconv" + + "cosmossdk.io/errors" +) + +type CrossChainPackageType uint8 + +type ChannelID uint8 +type ChainID uint16 + +const ( + SynCrossChainPackageType CrossChainPackageType = 0x00 + AckCrossChainPackageType CrossChainPackageType = 0x01 + FailAckCrossChainPackageType CrossChainPackageType = 0x02 +) + +type ChannelPermission uint8 + +const ( + ChannelAllow ChannelPermission = 1 + ChannelForbidden ChannelPermission = 0 +) + +func IsValidCrossChainPackageType(packageType CrossChainPackageType) bool { + return packageType == SynCrossChainPackageType || packageType == AckCrossChainPackageType || packageType == FailAckCrossChainPackageType +} + +func ParseChannelID(input string) (ChannelID, error) { + channelID, err := strconv.Atoi(input) + if err != nil { + return ChannelID(0), err + } + if channelID > math.MaxInt8 || channelID < 0 { + return ChannelID(0), fmt.Errorf("channelID must be in [0, 255]") + } + return ChannelID(channelID), nil +} + +func ParseChainID(input string) (ChainID, error) { + chainID, err := strconv.Atoi(input) + if err != nil { + return ChainID(0), err + } + if chainID > math.MaxUint16 || chainID < 0 { + return ChainID(0), fmt.Errorf("cross chainID must be in [0, 65535]") + } + return ChainID(chainID), nil +} + +type CrossChainApplication interface { + ExecuteSynPackage(ctx Context, payload []byte, relayerFee int64) ExecuteResult + ExecuteAckPackage(ctx Context, payload []byte) ExecuteResult + // When the ack application crash, payload is the payload of the origin package. + ExecuteFailAckPackage(ctx Context, payload []byte) ExecuteResult +} + +// TODO: define the execute result +type ExecuteResult struct { + Err errors.Error + Payload []byte +} + +const ( + CrossChainFeeLength = 32 + PackageTypeLength = 1 + TimestampLength = 8 + PackageHeaderLength = CrossChainFeeLength + TimestampLength + PackageTypeLength +) + +func EncodePackageHeader(packageType CrossChainPackageType, timestamp uint64, relayerFee big.Int) []byte { + packageHeader := make([]byte, PackageHeaderLength) + packageHeader[0] = uint8(packageType) + + timestampBytes := make([]byte, TimestampLength) + binary.BigEndian.PutUint64(timestampBytes, timestamp) + copy(packageHeader[CrossChainFeeLength:CrossChainFeeLength+TimestampLength], timestampBytes) + + length := len(relayerFee.Bytes()) + copy(packageHeader[PackageHeaderLength-length:PackageHeaderLength], relayerFee.Bytes()) + return packageHeader +} + +func DecodePackageHeader(packageHeader []byte) (packageType CrossChainPackageType, timestamp uint64, relayFee big.Int, err error) { + if len(packageHeader) < PackageHeaderLength { + err = fmt.Errorf("length of packageHeader is less than %d", PackageHeaderLength) + return + } + packageType = CrossChainPackageType(packageHeader[0]) + + timestamp = binary.BigEndian.Uint64(packageHeader[PackageTypeLength : CrossChainFeeLength+TimestampLength]) + + relayFee.SetBytes(packageHeader[PackageTypeLength+TimestampLength : PackageHeaderLength]) + return +} diff --git a/x/ibc/README.md b/x/ibc/README.md new file mode 100644 index 0000000000..f78a103b22 --- /dev/null +++ b/x/ibc/README.md @@ -0,0 +1,6 @@ + + +# IBC + diff --git a/x/ibc/keeper/config.go b/x/ibc/keeper/config.go new file mode 100644 index 0000000000..f2ac20c70b --- /dev/null +++ b/x/ibc/keeper/config.go @@ -0,0 +1,26 @@ +package keeper + +import sdk "github.com/cosmos/cosmos-sdk/types" + +type crossChainConfig struct { + srcChainID sdk.ChainID + + nameToChannelID map[string]sdk.ChannelID + channelIDToName map[sdk.ChannelID]string + channelIDToApp map[sdk.ChannelID]sdk.CrossChainApplication + + destChainNameToID map[string]sdk.ChainID + destChainIDToName map[sdk.ChainID]string +} + +func newCrossChainCfg() *crossChainConfig { + config := &crossChainConfig{ + srcChainID: 0, + nameToChannelID: make(map[string]sdk.ChannelID), + channelIDToName: make(map[sdk.ChannelID]string), + destChainNameToID: make(map[string]sdk.ChainID), + destChainIDToName: make(map[sdk.ChainID]string), + channelIDToApp: make(map[sdk.ChannelID]sdk.CrossChainApplication), + } + return config +} diff --git a/x/ibc/keeper/keeper.go b/x/ibc/keeper/keeper.go new file mode 100644 index 0000000000..7bd784a41a --- /dev/null +++ b/x/ibc/keeper/keeper.go @@ -0,0 +1,205 @@ +package keeper + +import ( + "encoding/binary" + "fmt" + "math/big" + + "github.com/tendermint/tendermint/libs/log" + + "github.com/cosmos/cosmos-sdk/bsc" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/ibc/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +// Keeper of the ibc store +type Keeper struct { + cdc codec.BinaryCodec + + cfg *crossChainConfig + storeKey storetypes.StoreKey + paramSpace paramtypes.Subspace +} + +// NewKeeper creates a new mint Keeper instance +func NewKeeper( + cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace paramtypes.Subspace, +) Keeper { + return Keeper{ + cdc: cdc, + storeKey: key, + paramSpace: paramSpace, + } +} + +func (k *Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", "x/"+types.ModuleName) +} + +func (k *Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { + var relayerFeeParam int64 + k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) + relayerFee = bsc.ConvertBCAmountToBSCAmount(relayerFeeParam) + return +} + +func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) +} + +func (k *Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, + packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) { + + relayerFee, err := k.GetRelayerFeeParam(ctx) + if err != nil { + return 0, fmt.Errorf("fail to load relayerFee, %v", err) + } + + return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) +} + +func (k *Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission { + kvStore := ctx.KVStore(k.storeKey) + bz := kvStore.Get(types.BuildChannelPermissionKey(destChainID, channelID)) + if bz == nil { + return sdk.ChannelForbidden + } + return sdk.ChannelPermission(bz[0]) +} + +func (k *Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, + packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int) (uint64, error) { + + if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, destChainID, channelID) != sdk.ChannelAllow { + return 0, fmt.Errorf("channel %d is not allowed to write syn package", channelID) + } + + sequence := k.GetSendSequence(ctx, destChainID, channelID) + key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelID, sequence) + kvStore := ctx.KVStore(k.storeKey) + if kvStore.Has(key) { + return 0, fmt.Errorf("duplicated sequence") + } + + // Assemble the package header + packageHeader := sdk.EncodePackageHeader(packageType, uint64(ctx.BlockTime().Unix()), relayerFee) + + kvStore.Set(key, append(packageHeader, packageLoad...)) + + k.IncrSendSequence(ctx, destChainID, channelID) + + err := ctx.EventManager().EmitTypedEvent(&types.EventIBCPackage{ + SrcChainId: uint32(k.GetSrcChainID()), + DestChainId: uint32(destChainID), + ChannelId: uint32(channelID), + Sequence: sequence, + PackageType: uint32(packageType), + Timestamp: uint64(ctx.BlockTime().Unix()), + PackageLoad: packageLoad, + RelayerFee: relayerFee.String(), + }) + if err != nil { + return 0, err + } + + return sequence, nil +} + +func (k *Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChainApplication) error { + _, ok := k.cfg.nameToChannelID[name] + if ok { + return fmt.Errorf("duplicated channel name") + } + _, ok = k.cfg.channelIDToName[id] + if ok { + return fmt.Errorf("duplicated channel id") + } + k.cfg.nameToChannelID[name] = id + k.cfg.channelIDToName[id] = name + k.cfg.channelIDToApp[id] = app + return nil +} + +func (k *Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { + _, ok := k.cfg.destChainNameToID[name] + if ok { + return fmt.Errorf("duplicated destination chain name") + } + _, ok = k.cfg.destChainIDToName[chainID] + if ok { + return fmt.Errorf("duplicated destination chain chainID") + } + k.cfg.destChainNameToID[name] = chainID + k.cfg.destChainIDToName[chainID] = name + return nil +} + +func (k *Keeper) SetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, permission sdk.ChannelPermission) { + kvStore := ctx.KVStore(k.storeKey) + kvStore.Set(types.BuildChannelPermissionKey(destChainID, channelID), []byte{byte(permission)}) +} + +func (k *Keeper) SetSrcChainID(srcChainID sdk.ChainID) { + k.cfg.srcChainID = srcChainID +} + +func (k *Keeper) GetSrcChainID() sdk.ChainID { + return k.cfg.srcChainID +} + +func (k *Keeper) GetDestChainID(name string) (sdk.ChainID, error) { + destChainID, exist := k.cfg.destChainNameToID[name] + if !exist { + return sdk.ChainID(0), fmt.Errorf("non-existing destination chainName ") + } + return destChainID, nil +} + +func (k *Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { + kvStore := ctx.KVStore(k.storeKey) + key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelId, sequence) + return kvStore.Get(key), nil +} + +func (k *Keeper) GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { + return k.getSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) +} + +func (k *Keeper) IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { + k.incrSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) +} + +func (k *Keeper) GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { + return k.getSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) +} + +func (k *Keeper) IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { + k.incrSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) +} + +func (k *Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) uint64 { + kvStore := ctx.KVStore(k.storeKey) + bz := kvStore.Get(types.BuildChannelSequenceKey(destChainID, channelID, prefix)) + if bz == nil { + return 0 + } + return binary.BigEndian.Uint64(bz) +} + +func (k *Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) { + var sequence uint64 + kvStore := ctx.KVStore(k.storeKey) + bz := kvStore.Get(types.BuildChannelSequenceKey(destChainID, channelID, prefix)) + if bz == nil { + sequence = 0 + } else { + sequence = binary.BigEndian.Uint64(bz) + } + + sequenceBytes := make([]byte, types.SequenceLength) + binary.BigEndian.PutUint64(sequenceBytes, sequence+1) + kvStore.Set(types.BuildChannelSequenceKey(destChainID, channelID, prefix), sequenceBytes) +} diff --git a/x/ibc/keeper/querier.go b/x/ibc/keeper/querier.go new file mode 100644 index 0000000000..dd1cc5e452 --- /dev/null +++ b/x/ibc/keeper/querier.go @@ -0,0 +1,19 @@ +package keeper + +import ( + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { + switch path[0] { + + default: + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) + } + } +} diff --git a/x/ibc/module.go b/x/ibc/module.go new file mode 100644 index 0000000000..bbbe86a324 --- /dev/null +++ b/x/ibc/module.go @@ -0,0 +1,135 @@ +package params + +import ( + "encoding/json" + "math/rand" + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/ibc/keeper" + "github.com/cosmos/cosmos-sdk/x/ibc/types" + "github.com/cosmos/cosmos-sdk/x/params/client/cli" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} +) + +// AppModuleBasic defines the basic application module used by the params module. +type AppModuleBasic struct{} + +// Name returns the params module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} + +// DefaultGenesis returns default genesis state as raw bytes for the params +// module. +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return nil } + +// ValidateGenesis performs genesis state validation for the params module. +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { + return nil +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + // TODO: fix this +} + +// GetTxCmd returns no root tx command for the params module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// GetQueryCmd returns no root query command for the params module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.NewQueryCmd() +} + +func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + // TODO: fix this +} + +// AppModule implements an application module for the distribution module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(k keeper.Keeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + } +} + +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs a no-op. +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// Deprecated: Route returns the message routing key for the params module. +func (AppModule) Route() sdk.Route { + return sdk.Route{} +} + +// GenerateGenesisState performs a no-op. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} + +// QuerierRoute returns the x/param module's querier route name. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the x/params querier handler. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return keeper.NewQuerier(am.keeper, legacyQuerierCdc) +} + +// RegisterServices registers a gRPC query service to respond to the +// module-specific gRPC queries. +func (am AppModule) RegisterServices(cfg module.Configurator) { + // TODO: fix this +} + +// ProposalContents returns all the params content functions used to +// simulate governance proposals. +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + return nil // TODO: fill this + //return simulation.ProposalContents(simState.ParamChanges) +} + +// RandomizedParams creates randomized distribution param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { + return nil +} + +// RegisterStoreDecoder doesn't register any type. +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return nil +} + +// ExportGenesis performs a no-op. +func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONCodec) json.RawMessage { + return nil +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/ibc/types/event.pb.go b/x/ibc/types/event.pb.go new file mode 100644 index 0000000000..71422e3c6e --- /dev/null +++ b/x/ibc/types/event.pb.go @@ -0,0 +1,589 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/ibc/v1/event.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + 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 EventIBCPackage struct { + SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` + DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` + ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` + PackageType uint32 `protobuf:"varint,5,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` + Timestamp uint64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + PackageLoad []byte `protobuf:"bytes,7,opt,name=package_load,json=packageLoad,proto3" json:"package_load,omitempty"` + RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` +} + +func (m *EventIBCPackage) Reset() { *m = EventIBCPackage{} } +func (m *EventIBCPackage) String() string { return proto.CompactTextString(m) } +func (*EventIBCPackage) ProtoMessage() {} +func (*EventIBCPackage) Descriptor() ([]byte, []int) { + return fileDescriptor_910737647fd17fb9, []int{0} +} +func (m *EventIBCPackage) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EventIBCPackage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EventIBCPackage.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 *EventIBCPackage) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventIBCPackage.Merge(m, src) +} +func (m *EventIBCPackage) XXX_Size() int { + return m.Size() +} +func (m *EventIBCPackage) XXX_DiscardUnknown() { + xxx_messageInfo_EventIBCPackage.DiscardUnknown(m) +} + +var xxx_messageInfo_EventIBCPackage proto.InternalMessageInfo + +func (m *EventIBCPackage) GetSrcChainId() uint32 { + if m != nil { + return m.SrcChainId + } + return 0 +} + +func (m *EventIBCPackage) GetDestChainId() uint32 { + if m != nil { + return m.DestChainId + } + return 0 +} + +func (m *EventIBCPackage) GetChannelId() uint32 { + if m != nil { + return m.ChannelId + } + return 0 +} + +func (m *EventIBCPackage) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + +func (m *EventIBCPackage) GetPackageType() uint32 { + if m != nil { + return m.PackageType + } + return 0 +} + +func (m *EventIBCPackage) GetTimestamp() uint64 { + if m != nil { + return m.Timestamp + } + return 0 +} + +func (m *EventIBCPackage) GetPackageLoad() []byte { + if m != nil { + return m.PackageLoad + } + return nil +} + +func (m *EventIBCPackage) GetRelayerFee() string { + if m != nil { + return m.RelayerFee + } + return "" +} + +func init() { + proto.RegisterType((*EventIBCPackage)(nil), "cosmos.authz.v1beta1.EventIBCPackage") +} + +func init() { proto.RegisterFile("cosmos/ibc/v1/event.proto", fileDescriptor_910737647fd17fb9) } + +var fileDescriptor_910737647fd17fb9 = []byte{ + // 323 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x41, 0x4f, 0xc2, 0x30, + 0x14, 0xc7, 0x29, 0x22, 0x42, 0x81, 0x98, 0x34, 0x1e, 0x26, 0xd1, 0x3a, 0x39, 0xed, 0xe2, 0x16, + 0xe2, 0x37, 0x80, 0x68, 0x42, 0xe2, 0xc1, 0x10, 0x4f, 0x5e, 0x96, 0xae, 0x7d, 0xb2, 0x05, 0xb6, + 0xce, 0xb5, 0x10, 0xf1, 0x53, 0x78, 0xf3, 0x2b, 0x79, 0xe4, 0xe8, 0xd1, 0xc0, 0x17, 0x31, 0xeb, + 0x2a, 0x78, 0x6a, 0xde, 0xaf, 0xbf, 0xf7, 0xcf, 0xcb, 0x7b, 0xf8, 0x9c, 0x4b, 0x95, 0x4a, 0x15, + 0x24, 0x11, 0x0f, 0x56, 0xc3, 0x00, 0x56, 0x90, 0x69, 0x3f, 0x2f, 0xa4, 0x96, 0xe4, 0xac, 0xfa, + 0xf2, 0xd9, 0x52, 0xc7, 0xef, 0xfe, 0x6a, 0x18, 0x81, 0x66, 0xc3, 0xbe, 0x6d, 0x08, 0x8d, 0x13, + 0x58, 0xc5, 0x14, 0x83, 0xcf, 0x3a, 0x3e, 0xbd, 0x2b, 0x03, 0x26, 0xa3, 0xf1, 0x23, 0xe3, 0x73, + 0x36, 0x03, 0xe2, 0xe2, 0xae, 0x2a, 0x78, 0xc8, 0x63, 0x96, 0x64, 0x61, 0x22, 0x1c, 0xe4, 0x22, + 0xaf, 0x37, 0xc5, 0xaa, 0xe0, 0xe3, 0x12, 0x4d, 0x04, 0x19, 0xe0, 0x9e, 0x00, 0xa5, 0x0f, 0x4a, + 0xdd, 0x28, 0x9d, 0x12, 0xfe, 0x39, 0x97, 0x18, 0xf3, 0x98, 0x65, 0x19, 0x2c, 0x4a, 0xe1, 0xc8, + 0x08, 0x6d, 0x4b, 0x26, 0x82, 0xf4, 0x71, 0x4b, 0xc1, 0xeb, 0x12, 0x32, 0x0e, 0x4e, 0xc3, 0x45, + 0x5e, 0x63, 0xba, 0xaf, 0xc9, 0x35, 0xee, 0xe6, 0xd5, 0x2c, 0xa1, 0x5e, 0xe7, 0xe0, 0x1c, 0x57, + 0xe9, 0x96, 0x3d, 0xad, 0x73, 0x20, 0x17, 0xb8, 0xad, 0x93, 0x14, 0x94, 0x66, 0x69, 0xee, 0x34, + 0x4d, 0xff, 0x01, 0xfc, 0x0f, 0x58, 0x48, 0x26, 0x9c, 0x13, 0x17, 0x79, 0xdd, 0x7d, 0xc0, 0x83, + 0x64, 0x82, 0x5c, 0xe1, 0x4e, 0x01, 0x0b, 0xb6, 0x86, 0x22, 0x7c, 0x01, 0x70, 0x5a, 0x2e, 0xf2, + 0xda, 0x53, 0x6c, 0xd1, 0x3d, 0xc0, 0x68, 0xf4, 0xb5, 0xa5, 0x68, 0xb3, 0xa5, 0xe8, 0x67, 0x4b, + 0xd1, 0xc7, 0x8e, 0xd6, 0x36, 0x3b, 0x5a, 0xfb, 0xde, 0xd1, 0xda, 0xb3, 0x37, 0x4b, 0x74, 0xbc, + 0x8c, 0x7c, 0x2e, 0x53, 0xbb, 0x4c, 0xfb, 0xdc, 0x28, 0x31, 0x0f, 0xde, 0xcc, 0x5d, 0xca, 0xb9, + 0x55, 0xd4, 0x34, 0x4b, 0xbe, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x74, 0xd6, 0x36, 0x01, 0xb2, + 0x01, 0x00, 0x00, +} + +func (m *EventIBCPackage) 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 *EventIBCPackage) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EventIBCPackage) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.RelayerFee) > 0 { + i -= len(m.RelayerFee) + copy(dAtA[i:], m.RelayerFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.RelayerFee))) + i-- + dAtA[i] = 0x42 + } + if len(m.PackageLoad) > 0 { + i -= len(m.PackageLoad) + copy(dAtA[i:], m.PackageLoad) + i = encodeVarintEvent(dAtA, i, uint64(len(m.PackageLoad))) + i-- + dAtA[i] = 0x3a + } + if m.Timestamp != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.Timestamp)) + i-- + dAtA[i] = 0x30 + } + if m.PackageType != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.PackageType)) + i-- + dAtA[i] = 0x28 + } + if m.Sequence != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.Sequence)) + i-- + dAtA[i] = 0x20 + } + if m.ChannelId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.ChannelId)) + i-- + dAtA[i] = 0x18 + } + if m.DestChainId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.DestChainId)) + i-- + dAtA[i] = 0x10 + } + if m.SrcChainId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.SrcChainId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintEvent(dAtA []byte, offset int, v uint64) int { + offset -= sovEvent(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *EventIBCPackage) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.SrcChainId != 0 { + n += 1 + sovEvent(uint64(m.SrcChainId)) + } + if m.DestChainId != 0 { + n += 1 + sovEvent(uint64(m.DestChainId)) + } + if m.ChannelId != 0 { + n += 1 + sovEvent(uint64(m.ChannelId)) + } + if m.Sequence != 0 { + n += 1 + sovEvent(uint64(m.Sequence)) + } + if m.PackageType != 0 { + n += 1 + sovEvent(uint64(m.PackageType)) + } + if m.Timestamp != 0 { + n += 1 + sovEvent(uint64(m.Timestamp)) + } + l = len(m.PackageLoad) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) + } + l = len(m.RelayerFee) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) + } + return n +} + +func sovEvent(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozEvent(x uint64) (n int) { + return sovEvent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *EventIBCPackage) 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 ErrIntOverflowEvent + } + 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: EventIBCPackage: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EventIBCPackage: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SrcChainId", wireType) + } + m.SrcChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SrcChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DestChainId", wireType) + } + m.DestChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DestChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) + } + m.ChannelId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PackageType", wireType) + } + m.PackageType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PackageType |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + m.Timestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Timestamp |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field PackageLoad", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthEvent + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.PackageLoad = append(m.PackageLoad[:0], dAtA[iNdEx:postIndex]...) + if m.PackageLoad == nil { + m.PackageLoad = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayerFee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + 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 ErrInvalidLengthEvent + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RelayerFee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipEvent(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvent + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipEvent(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, ErrIntOverflowEvent + } + 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, ErrIntOverflowEvent + } + 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, ErrIntOverflowEvent + } + 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, ErrInvalidLengthEvent + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupEvent + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthEvent + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthEvent = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowEvent = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupEvent = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/ibc/types/expected_keepers.go b/x/ibc/types/expected_keepers.go new file mode 100644 index 0000000000..804c94d571 --- /dev/null +++ b/x/ibc/types/expected_keepers.go @@ -0,0 +1,10 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +type CrossChainKeeper interface { + GetSrcChainID() sdk.ChainID + IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) + GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission + GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 +} diff --git a/x/ibc/types/ibc.pb.go b/x/ibc/types/ibc.pb.go new file mode 100644 index 0000000000..bd7fe09c8c --- /dev/null +++ b/x/ibc/types/ibc.pb.go @@ -0,0 +1,303 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/ibc/v1/ibc.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/gogo/protobuf/gogoproto" + 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 + +// Params holds parameters for the mint module. +type Params struct { + RelayerFee uint64 `protobuf:"varint,1,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_f4c036912cdbae97, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func (m *Params) GetRelayerFee() uint64 { + if m != nil { + return m.RelayerFee + } + return 0 +} + +func init() { + proto.RegisterType((*Params)(nil), "cosmos.ibc.v1.Params") +} + +func init() { proto.RegisterFile("cosmos/ibc/v1/ibc.proto", fileDescriptor_f4c036912cdbae97) } + +var fileDescriptor_f4c036912cdbae97 = []byte{ + // 178 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x4c, 0x4a, 0xd6, 0x2f, 0x33, 0x04, 0x51, 0x7a, 0x05, 0x45, 0xf9, 0x25, + 0xf9, 0x42, 0xbc, 0x10, 0x09, 0x3d, 0x90, 0x48, 0x99, 0xa1, 0x94, 0x48, 0x7a, 0x7e, 0x7a, 0x3e, + 0x58, 0x46, 0x1f, 0xc4, 0x82, 0x28, 0x92, 0x92, 0x84, 0x28, 0x8a, 0x87, 0x48, 0x40, 0x75, 0x80, + 0x39, 0x4a, 0x9a, 0x5c, 0x6c, 0x01, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x42, 0xf2, 0x5c, 0xdc, 0x45, + 0xa9, 0x39, 0x89, 0x95, 0xa9, 0x45, 0xf1, 0x69, 0xa9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x2c, + 0x41, 0x5c, 0x50, 0x21, 0xb7, 0xd4, 0x54, 0x27, 0xa7, 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, 0x48, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85, 0x9a, + 0x0e, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0xc0, 0xae, 0x2e, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, + 0x62, 0x03, 0xdb, 0x6a, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xfa, 0x4c, 0xfd, 0xd0, 0x00, + 0x00, 0x00, +} + +func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.RelayerFee != 0 { + i = encodeVarintIbc(dAtA, i, uint64(m.RelayerFee)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintIbc(dAtA []byte, offset int, v uint64) int { + offset -= sovIbc(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.RelayerFee != 0 { + n += 1 + sovIbc(uint64(m.RelayerFee)) + } + return n +} + +func sovIbc(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozIbc(x uint64) (n int) { + return sovIbc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) 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 ErrIntOverflowIbc + } + 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: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayerFee", wireType) + } + m.RelayerFee = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowIbc + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RelayerFee |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipIbc(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthIbc + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipIbc(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, ErrIntOverflowIbc + } + 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, ErrIntOverflowIbc + } + 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, ErrIntOverflowIbc + } + 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, ErrInvalidLengthIbc + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupIbc + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthIbc + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthIbc = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowIbc = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupIbc = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/ibc/types/keys.go b/x/ibc/types/keys.go new file mode 100644 index 0000000000..15dbd9cf09 --- /dev/null +++ b/x/ibc/types/keys.go @@ -0,0 +1,93 @@ +package types + +import ( + "encoding/binary" + "fmt" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + ModuleName = "ibc" + StoreKey = ModuleName + QuerierRoute = StoreKey + + prefixLength = 1 + srcChainIdLength = 2 + destChainIDLength = 2 + channelIDLength = 1 + sequenceLength = 8 + + totalPackageKeyLength = prefixLength + srcChainIdLength + destChainIDLength + channelIDLength + sequenceLength + + MaxSideChainIdLength = 20 + SequenceLength = 8 + + GovChannelId = sdk.ChannelID(9) +) + +var ( + PrefixForIbcPackageKey = []byte{0x00} + + PrefixForSendSequenceKey = []byte{0xf0} + PrefixForReceiveSequenceKey = []byte{0xf1} + + PrefixForChannelPermissionKey = []byte{0xc0} +) + +func BuildIBCPackageKey(srcChainID, destChainID sdk.ChainID, channelID sdk.ChannelID, sequence uint64) []byte { + key := make([]byte, totalPackageKeyLength) + + copy(key[:prefixLength], PrefixForIbcPackageKey) + binary.BigEndian.PutUint16(key[prefixLength:srcChainIdLength+prefixLength], uint16(srcChainID)) + binary.BigEndian.PutUint16(key[prefixLength+srcChainIdLength:prefixLength+srcChainIdLength+destChainIDLength], uint16(destChainID)) + copy(key[prefixLength+srcChainIdLength+destChainIDLength:], []byte{byte(channelID)}) + binary.BigEndian.PutUint64(key[prefixLength+srcChainIdLength+destChainIDLength+channelIDLength:], sequence) + + return key +} + +type ChannelPermissionSetting struct { + SideChainId string `json:"side_chain_id"` + ChannelId sdk.ChannelID `json:"channel_id"` + Permission sdk.ChannelPermission `json:"permission"` +} + +func (c *ChannelPermissionSetting) Check() error { + if len(c.SideChainId) == 0 || len(c.SideChainId) > MaxSideChainIdLength { + return fmt.Errorf("invalid side chain id") + } + if c.ChannelId == GovChannelId { + return fmt.Errorf("gov channel id is forbidden to set") + } + if c.Permission != sdk.ChannelAllow && c.Permission != sdk.ChannelForbidden { + return fmt.Errorf("permission %d is invalid", c.Permission) + } + return nil +} + +func BuildChannelSequenceKey(destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) []byte { + key := make([]byte, prefixLength+destChainIDLength+channelIDLength) + + copy(key[:prefixLength], prefix) + binary.BigEndian.PutUint16(key[prefixLength:prefixLength+destChainIDLength], uint16(destChainID)) + copy(key[prefixLength+destChainIDLength:], []byte{byte(channelID)}) + return key +} + +func BuildChannelPermissionKey(destChainID sdk.ChainID, channelID sdk.ChannelID) []byte { + key := make([]byte, prefixLength+destChainIDLength+channelIDLength) + + copy(key[:prefixLength], PrefixForChannelPermissionKey) + binary.BigEndian.PutUint16(key[prefixLength:prefixLength+destChainIDLength], uint16(destChainID)) + copy(key[prefixLength+destChainIDLength:], []byte{byte(channelID)}) + return key +} + +func BuildChannelPermissionsPrefixKey(destChainID sdk.ChainID) []byte { + key := make([]byte, prefixLength+destChainIDLength) + + copy(key[:prefixLength], PrefixForChannelPermissionKey) + binary.BigEndian.PutUint16(key[prefixLength:prefixLength+destChainIDLength], uint16(destChainID)) + return key +} diff --git a/x/ibc/types/params.go b/x/ibc/types/params.go new file mode 100644 index 0000000000..02ea050035 --- /dev/null +++ b/x/ibc/types/params.go @@ -0,0 +1,45 @@ +package types + +import ( + "fmt" + + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +const ( + DefaultRelayerFeeParam uint64 = 1e6 // decimal is 8 +) + +var ( + KeyParamRelayerFee = []byte("relayerFee") +) + +func DefaultParams() Params { + return Params{ + RelayerFee: DefaultRelayerFeeParam, + } +} + +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// ParamSetPairs implements params.ParamSet +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(KeyParamRelayerFee, p.RelayerFee, validateRelayerFee), + } +} + +func validateRelayerFee(i interface{}) error { + v, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v <= 0 { + return fmt.Errorf("the syn_package_fee must be positive: %d", v) + } + + return nil +} From c5deb8b2f698ff577d2bf00babb1210009be37bf Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 15 Nov 2022 15:27:19 +0800 Subject: [PATCH 02/50] add ibc querier --- proto/cosmos/ibc/v1/query.proto | 39 +-- x/ibc/keeper/grpc_query.go | 18 ++ x/ibc/keeper/keeper.go | 43 +-- x/ibc/keeper/querier.go | 14 + x/ibc/module.go | 14 +- x/ibc/types/keys.go | 2 + x/ibc/types/query.pb.go | 535 ++++++++++++++++++++++++++++++++ x/ibc/types/query.pb.gw.go | 153 +++++++++ 8 files changed, 757 insertions(+), 61 deletions(-) create mode 100644 x/ibc/keeper/grpc_query.go create mode 100644 x/ibc/types/query.pb.go create mode 100644 x/ibc/types/query.pb.gw.go diff --git a/proto/cosmos/ibc/v1/query.proto b/proto/cosmos/ibc/v1/query.proto index b7e7553b3e..a82674f17f 100644 --- a/proto/cosmos/ibc/v1/query.proto +++ b/proto/cosmos/ibc/v1/query.proto @@ -1,8 +1,9 @@ syntax = "proto3"; -package cosmos.mint.v1beta1; +package cosmos.ibc.v1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; +import "cosmos/ibc/v1/ibc.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; @@ -10,17 +11,7 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; service Query { // Params returns the total set of minting parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/cosmos/mint/v1beta1/params"; - } - - // Inflation returns the current minting inflation value. - rpc Inflation(QueryInflationRequest) returns (QueryInflationResponse) { - option (google.api.http).get = "/cosmos/mint/v1beta1/inflation"; - } - - // AnnualProvisions current minting annual provisions value. - rpc AnnualProvisions(QueryAnnualProvisionsRequest) returns (QueryAnnualProvisionsResponse) { - option (google.api.http).get = "/cosmos/mint/v1beta1/annual_provisions"; + option (google.api.http).get = "/cosmos/ibc/v1/params"; } } @@ -31,26 +22,4 @@ message QueryParamsRequest {} message QueryParamsResponse { // params defines the parameters of the module. Params params = 1 [(gogoproto.nullable) = false]; -} - -// QueryInflationRequest is the request type for the Query/Inflation RPC method. -message QueryInflationRequest {} - -// QueryInflationResponse is the response type for the Query/Inflation RPC -// method. -message QueryInflationResponse { - // inflation is the current minting inflation value. - bytes inflation = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} - -// QueryAnnualProvisionsRequest is the request type for the -// Query/AnnualProvisions RPC method. -message QueryAnnualProvisionsRequest {} - -// QueryAnnualProvisionsResponse is the response type for the -// Query/AnnualProvisions RPC method. -message QueryAnnualProvisionsResponse { - // annual_provisions is the current minting annual provisions value. - bytes annual_provisions = 1 - [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; -} +} \ No newline at end of file diff --git a/x/ibc/keeper/grpc_query.go b/x/ibc/keeper/grpc_query.go new file mode 100644 index 0000000000..1b6c87ea12 --- /dev/null +++ b/x/ibc/keeper/grpc_query.go @@ -0,0 +1,18 @@ +package keeper + +import ( + "context" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/ibc/types" +) + +var _ types.QueryServer = Keeper{} + +// Params returns params of the mint module. +func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + params := k.GetParams(ctx) + + return &types.QueryParamsResponse{Params: params}, nil +} diff --git a/x/ibc/keeper/keeper.go b/x/ibc/keeper/keeper.go index 7bd784a41a..54a0e288c1 100644 --- a/x/ibc/keeper/keeper.go +++ b/x/ibc/keeper/keeper.go @@ -35,22 +35,22 @@ func NewKeeper( } } -func (k *Keeper) Logger(ctx sdk.Context) log.Logger { +func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } -func (k *Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { +func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { var relayerFeeParam int64 k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) relayerFee = bsc.ConvertBCAmountToBSCAmount(relayerFeeParam) return } -func (k *Keeper) SetParams(ctx sdk.Context, params types.Params) { +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) } -func (k *Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, +func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) { relayerFee, err := k.GetRelayerFeeParam(ctx) @@ -61,7 +61,7 @@ func (k *Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, c return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) } -func (k *Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission { +func (k Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission { kvStore := ctx.KVStore(k.storeKey) bz := kvStore.Get(types.BuildChannelPermissionKey(destChainID, channelID)) if bz == nil { @@ -70,7 +70,7 @@ func (k *Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.Chain return sdk.ChannelPermission(bz[0]) } -func (k *Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, +func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int) (uint64, error) { if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, destChainID, channelID) != sdk.ChannelAllow { @@ -108,7 +108,7 @@ func (k *Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Cha return sequence, nil } -func (k *Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChainApplication) error { +func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChainApplication) error { _, ok := k.cfg.nameToChannelID[name] if ok { return fmt.Errorf("duplicated channel name") @@ -123,7 +123,7 @@ func (k *Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossCha return nil } -func (k *Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { +func (k Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { _, ok := k.cfg.destChainNameToID[name] if ok { return fmt.Errorf("duplicated destination chain name") @@ -137,20 +137,20 @@ func (k *Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { return nil } -func (k *Keeper) SetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, permission sdk.ChannelPermission) { +func (k Keeper) SetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, permission sdk.ChannelPermission) { kvStore := ctx.KVStore(k.storeKey) kvStore.Set(types.BuildChannelPermissionKey(destChainID, channelID), []byte{byte(permission)}) } -func (k *Keeper) SetSrcChainID(srcChainID sdk.ChainID) { +func (k Keeper) SetSrcChainID(srcChainID sdk.ChainID) { k.cfg.srcChainID = srcChainID } -func (k *Keeper) GetSrcChainID() sdk.ChainID { +func (k Keeper) GetSrcChainID() sdk.ChainID { return k.cfg.srcChainID } -func (k *Keeper) GetDestChainID(name string) (sdk.ChainID, error) { +func (k Keeper) GetDestChainID(name string) (sdk.ChainID, error) { destChainID, exist := k.cfg.destChainNameToID[name] if !exist { return sdk.ChainID(0), fmt.Errorf("non-existing destination chainName ") @@ -158,29 +158,29 @@ func (k *Keeper) GetDestChainID(name string) (sdk.ChainID, error) { return destChainID, nil } -func (k *Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { +func (k Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { kvStore := ctx.KVStore(k.storeKey) key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelId, sequence) return kvStore.Get(key), nil } -func (k *Keeper) GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { +func (k Keeper) GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { return k.getSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) } -func (k *Keeper) IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { +func (k Keeper) IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { k.incrSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) } -func (k *Keeper) GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { +func (k Keeper) GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { return k.getSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) } -func (k *Keeper) IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { +func (k Keeper) IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { k.incrSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) } -func (k *Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) uint64 { +func (k Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) uint64 { kvStore := ctx.KVStore(k.storeKey) bz := kvStore.Get(types.BuildChannelSequenceKey(destChainID, channelID, prefix)) if bz == nil { @@ -189,7 +189,7 @@ func (k *Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID return binary.BigEndian.Uint64(bz) } -func (k *Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) { +func (k Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) { var sequence uint64 kvStore := ctx.KVStore(k.storeKey) bz := kvStore.Get(types.BuildChannelSequenceKey(destChainID, channelID, prefix)) @@ -203,3 +203,8 @@ func (k *Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelI binary.BigEndian.PutUint64(sequenceBytes, sequence+1) kvStore.Set(types.BuildChannelSequenceKey(destChainID, channelID, prefix), sequenceBytes) } + +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params +} diff --git a/x/ibc/keeper/querier.go b/x/ibc/keeper/querier.go index dd1cc5e452..cd295b23ca 100644 --- a/x/ibc/keeper/querier.go +++ b/x/ibc/keeper/querier.go @@ -6,14 +6,28 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/x/ibc/types" ) func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { + case types.QueryParameters: + return queryParams(ctx, k, legacyQuerierCdc) default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) } } } + +func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { + params := k.GetParams(ctx) + + res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + + return res, nil +} diff --git a/x/ibc/module.go b/x/ibc/module.go index bbbe86a324..5f113ad1c7 100644 --- a/x/ibc/module.go +++ b/x/ibc/module.go @@ -1,6 +1,7 @@ package params import ( + "context" "encoding/json" "math/rand" @@ -47,7 +48,9 @@ func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodin // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - // TODO: fix this + if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil { + panic(err) + } } // GetTxCmd returns no root tx command for the params module. @@ -58,9 +61,7 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.NewQueryCmd() } -func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { - // TODO: fix this -} +func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {} // AppModule implements an application module for the distribution module. type AppModule struct { @@ -103,14 +104,13 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // RegisterServices registers a gRPC query service to respond to the // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { - // TODO: fix this + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) } // ProposalContents returns all the params content functions used to // simulate governance proposals. func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { - return nil // TODO: fill this - //return simulation.ProposalContents(simState.ParamChanges) + return nil } // RandomizedParams creates randomized distribution param changes for the simulator. diff --git a/x/ibc/types/keys.go b/x/ibc/types/keys.go index 15dbd9cf09..060770a641 100644 --- a/x/ibc/types/keys.go +++ b/x/ibc/types/keys.go @@ -24,6 +24,8 @@ const ( SequenceLength = 8 GovChannelId = sdk.ChannelID(9) + + QueryParameters = "parameters" ) var ( diff --git a/x/ibc/types/query.pb.go b/x/ibc/types/query.pb.go new file mode 100644 index 0000000000..c63c8a9dbc --- /dev/null +++ b/x/ibc/types/query.pb.go @@ -0,0 +1,535 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/ibc/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryParamsRequest is the request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_0ec2ac3c289eec95, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is the response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params defines the parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_0ec2ac3c289eec95, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.ibc.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.ibc.v1.QueryParamsResponse") +} + +func init() { proto.RegisterFile("cosmos/ibc/v1/query.proto", fileDescriptor_0ec2ac3c289eec95) } + +var fileDescriptor_0ec2ac3c289eec95 = []byte{ + // 273 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x4c, 0x4a, 0xd6, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x85, 0x48, 0xe9, 0x65, 0x26, 0x25, 0xeb, 0x95, 0x19, + 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x65, 0xf4, 0x41, 0x2c, 0x88, 0x22, 0x29, 0x99, 0xf4, + 0xfc, 0xfc, 0xf4, 0x9c, 0x54, 0xfd, 0xc4, 0x82, 0x4c, 0xfd, 0xc4, 0xbc, 0xbc, 0xfc, 0x92, 0xc4, + 0x92, 0xcc, 0xfc, 0xbc, 0x62, 0xa8, 0xac, 0x38, 0xaa, 0xe9, 0x20, 0x93, 0xc0, 0x12, 0x4a, 0x22, + 0x5c, 0x42, 0x81, 0x20, 0xab, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x83, 0x52, 0x0b, 0x4b, 0x53, + 0x8b, 0x4b, 0x94, 0xbc, 0xb8, 0x84, 0x51, 0x44, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x8c, + 0xb9, 0xd8, 0x0a, 0xc0, 0x22, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0xa2, 0x7a, 0x28, 0x2e, + 0xd3, 0x83, 0x28, 0x77, 0x62, 0x39, 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xaa, 0xd4, 0xa8, 0x9c, 0x8b, + 0x15, 0x6c, 0x96, 0x50, 0x1e, 0x17, 0x1b, 0x44, 0x81, 0x90, 0x22, 0x9a, 0x3e, 0x4c, 0x17, 0x48, + 0x29, 0xe1, 0x53, 0x02, 0x71, 0x8e, 0x92, 0x6c, 0xd3, 0xe5, 0x27, 0x93, 0x99, 0xc4, 0x85, 0x44, + 0xf5, 0x51, 0x7d, 0x07, 0xb1, 0xd8, 0xc9, 0xe9, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, + 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, + 0x18, 0xa2, 0x34, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0x61, 0x5a, 0x21, + 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, 0x05, 0xd8, 0x9c, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, + 0x70, 0x28, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd8, 0x19, 0x86, 0x24, 0x9e, 0x01, 0x00, + 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + // Params returns the total set of minting parameters. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/cosmos.ibc.v1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + // Params returns the total set of minting parameters. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.ibc.v1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.ibc.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/ibc/v1/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/ibc/types/query.pb.gw.go b/x/ibc/types/query.pb.gw.go new file mode 100644 index 0000000000..7f2a67f5b4 --- /dev/null +++ b/x/ibc/types/query.pb.gw.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cosmos/ibc/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "ibc", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage +) From c4b35815cae599312dac215b440f556d8b41dbee Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 15 Nov 2022 15:38:52 +0800 Subject: [PATCH 03/50] rename module to crosschain --- proto/cosmos/crosschain/v1/crosschain.proto | 12 ++ .../cosmos/{ibc => crosschain}/v1/event.proto | 6 +- .../cosmos/{ibc => crosschain}/v1/query.proto | 8 +- proto/cosmos/ibc/v1/ibc.proto | 13 --- x/{ibc => crosschain}/README.md | 0 x/{ibc => crosschain}/keeper/config.go | 0 x/{ibc => crosschain}/keeper/grpc_query.go | 2 +- x/{ibc => crosschain}/keeper/keeper.go | 4 +- x/{ibc => crosschain}/keeper/querier.go | 2 +- x/{ibc => crosschain}/module.go | 4 +- .../types/crosschain.pb.go} | 82 ++++++------- x/{ibc => crosschain}/types/event.pb.go | 108 +++++++++--------- .../types/expected_keepers.go | 0 x/{ibc => crosschain}/types/keys.go | 0 x/{ibc => crosschain}/types/params.go | 0 x/{ibc => crosschain}/types/query.pb.go | 66 +++++------ x/{ibc => crosschain}/types/query.pb.gw.go | 4 +- 17 files changed, 156 insertions(+), 155 deletions(-) create mode 100644 proto/cosmos/crosschain/v1/crosschain.proto rename proto/cosmos/{ibc => crosschain}/v1/event.proto (68%) rename proto/cosmos/{ibc => crosschain}/v1/query.proto (73%) delete mode 100644 proto/cosmos/ibc/v1/ibc.proto rename x/{ibc => crosschain}/README.md (100%) rename x/{ibc => crosschain}/keeper/config.go (100%) rename x/{ibc => crosschain}/keeper/grpc_query.go (88%) rename x/{ibc => crosschain}/keeper/keeper.go (98%) rename x/{ibc => crosschain}/keeper/querier.go (94%) rename x/{ibc => crosschain}/module.go (97%) rename x/{ibc/types/ibc.pb.go => crosschain/types/crosschain.pb.go} (66%) rename x/{ibc => crosschain}/types/event.pb.go (72%) rename x/{ibc => crosschain}/types/expected_keepers.go (100%) rename x/{ibc => crosschain}/types/keys.go (100%) rename x/{ibc => crosschain}/types/params.go (100%) rename x/{ibc => crosschain}/types/query.pb.go (83%) rename x/{ibc => crosschain}/types/query.pb.gw.go (97%) diff --git a/proto/cosmos/crosschain/v1/crosschain.proto b/proto/cosmos/crosschain/v1/crosschain.proto new file mode 100644 index 0000000000..36c6cc6e0a --- /dev/null +++ b/proto/cosmos/crosschain/v1/crosschain.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package cosmos.crosschain.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +// Params holds parameters for the cross chain module. +message Params { + uint64 relayer_fee = 1; +} diff --git a/proto/cosmos/ibc/v1/event.proto b/proto/cosmos/crosschain/v1/event.proto similarity index 68% rename from proto/cosmos/ibc/v1/event.proto rename to proto/cosmos/crosschain/v1/event.proto index cdd6fcf2bc..8df6ddb7b1 100644 --- a/proto/cosmos/ibc/v1/event.proto +++ b/proto/cosmos/crosschain/v1/event.proto @@ -1,12 +1,12 @@ // Since: cosmos-sdk 0.43 syntax = "proto3"; -package cosmos.authz.v1beta1; +package cosmos.crosschain.v1; import "cosmos_proto/cosmos.proto"; -option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; +option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; -message EventIBCPackage { +message EventCrossChainPackage { uint32 src_chain_id = 1; uint32 dest_chain_id = 2; uint32 channel_id = 3; diff --git a/proto/cosmos/ibc/v1/query.proto b/proto/cosmos/crosschain/v1/query.proto similarity index 73% rename from proto/cosmos/ibc/v1/query.proto rename to proto/cosmos/crosschain/v1/query.proto index a82674f17f..a6fe71c2ca 100644 --- a/proto/cosmos/ibc/v1/query.proto +++ b/proto/cosmos/crosschain/v1/query.proto @@ -1,17 +1,17 @@ syntax = "proto3"; -package cosmos.ibc.v1; +package cosmos.crosschain.v1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; -import "cosmos/ibc/v1/ibc.proto"; +import "cosmos/crosschain/v1/crosschain.proto"; -option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; +option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; // Query provides defines the gRPC querier service. service Query { // Params returns the total set of minting parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { - option (google.api.http).get = "/cosmos/ibc/v1/params"; + option (google.api.http).get = "/cosmos/crosschain/v1/params"; } } diff --git a/proto/cosmos/ibc/v1/ibc.proto b/proto/cosmos/ibc/v1/ibc.proto deleted file mode 100644 index 2b9c512e76..0000000000 --- a/proto/cosmos/ibc/v1/ibc.proto +++ /dev/null @@ -1,13 +0,0 @@ -syntax = "proto3"; -package cosmos.ibc.v1; - -option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/types"; - -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; - -// Params holds parameters for the mint module. -message Params { - uint64 relayer_fee = 1; -} - diff --git a/x/ibc/README.md b/x/crosschain/README.md similarity index 100% rename from x/ibc/README.md rename to x/crosschain/README.md diff --git a/x/ibc/keeper/config.go b/x/crosschain/keeper/config.go similarity index 100% rename from x/ibc/keeper/config.go rename to x/crosschain/keeper/config.go diff --git a/x/ibc/keeper/grpc_query.go b/x/crosschain/keeper/grpc_query.go similarity index 88% rename from x/ibc/keeper/grpc_query.go rename to x/crosschain/keeper/grpc_query.go index 1b6c87ea12..8bfa3b2957 100644 --- a/x/ibc/keeper/grpc_query.go +++ b/x/crosschain/keeper/grpc_query.go @@ -4,7 +4,7 @@ import ( "context" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/ibc/types" + "github.com/cosmos/cosmos-sdk/x/crosschain/types" ) var _ types.QueryServer = Keeper{} diff --git a/x/ibc/keeper/keeper.go b/x/crosschain/keeper/keeper.go similarity index 98% rename from x/ibc/keeper/keeper.go rename to x/crosschain/keeper/keeper.go index 54a0e288c1..4d840cf231 100644 --- a/x/ibc/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -11,7 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/ibc/types" + "github.com/cosmos/cosmos-sdk/x/crosschain/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -91,7 +91,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai k.IncrSendSequence(ctx, destChainID, channelID) - err := ctx.EventManager().EmitTypedEvent(&types.EventIBCPackage{ + err := ctx.EventManager().EmitTypedEvent(&types.EventCrossChainPackage{ SrcChainId: uint32(k.GetSrcChainID()), DestChainId: uint32(destChainID), ChannelId: uint32(channelID), diff --git a/x/ibc/keeper/querier.go b/x/crosschain/keeper/querier.go similarity index 94% rename from x/ibc/keeper/querier.go rename to x/crosschain/keeper/querier.go index cd295b23ca..5c081a3c6f 100644 --- a/x/ibc/keeper/querier.go +++ b/x/crosschain/keeper/querier.go @@ -6,7 +6,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/ibc/types" + "github.com/cosmos/cosmos-sdk/x/crosschain/types" ) func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { diff --git a/x/ibc/module.go b/x/crosschain/module.go similarity index 97% rename from x/ibc/module.go rename to x/crosschain/module.go index 5f113ad1c7..7524e8f0db 100644 --- a/x/ibc/module.go +++ b/x/crosschain/module.go @@ -15,8 +15,8 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" simtypes "github.com/cosmos/cosmos-sdk/types/simulation" - "github.com/cosmos/cosmos-sdk/x/ibc/keeper" - "github.com/cosmos/cosmos-sdk/x/ibc/types" + "github.com/cosmos/cosmos-sdk/x/crosschain/keeper" + "github.com/cosmos/cosmos-sdk/x/crosschain/types" "github.com/cosmos/cosmos-sdk/x/params/client/cli" ) diff --git a/x/ibc/types/ibc.pb.go b/x/crosschain/types/crosschain.pb.go similarity index 66% rename from x/ibc/types/ibc.pb.go rename to x/crosschain/types/crosschain.pb.go index bd7fe09c8c..a1faabfc13 100644 --- a/x/ibc/types/ibc.pb.go +++ b/x/crosschain/types/crosschain.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/ibc/v1/ibc.proto +// source: cosmos/crosschain/v1/crosschain.proto package types @@ -24,7 +24,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -// Params holds parameters for the mint module. +// Params holds parameters for the cross chain module. type Params struct { RelayerFee uint64 `protobuf:"varint,1,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` } @@ -33,7 +33,7 @@ func (m *Params) Reset() { *m = Params{} } func (m *Params) String() string { return proto.CompactTextString(m) } func (*Params) ProtoMessage() {} func (*Params) Descriptor() ([]byte, []int) { - return fileDescriptor_f4c036912cdbae97, []int{0} + return fileDescriptor_d7b94a7254cf916a, []int{0} } func (m *Params) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -70,25 +70,27 @@ func (m *Params) GetRelayerFee() uint64 { } func init() { - proto.RegisterType((*Params)(nil), "cosmos.ibc.v1.Params") + proto.RegisterType((*Params)(nil), "cosmos.crosschain.v1.Params") } -func init() { proto.RegisterFile("cosmos/ibc/v1/ibc.proto", fileDescriptor_f4c036912cdbae97) } +func init() { + proto.RegisterFile("cosmos/crosschain/v1/crosschain.proto", fileDescriptor_d7b94a7254cf916a) +} -var fileDescriptor_f4c036912cdbae97 = []byte{ - // 178 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x12, 0x4f, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0xcf, 0x4c, 0x4a, 0xd6, 0x2f, 0x33, 0x04, 0x51, 0x7a, 0x05, 0x45, 0xf9, 0x25, - 0xf9, 0x42, 0xbc, 0x10, 0x09, 0x3d, 0x90, 0x48, 0x99, 0xa1, 0x94, 0x48, 0x7a, 0x7e, 0x7a, 0x3e, - 0x58, 0x46, 0x1f, 0xc4, 0x82, 0x28, 0x92, 0x92, 0x84, 0x28, 0x8a, 0x87, 0x48, 0x40, 0x75, 0x80, - 0x39, 0x4a, 0x9a, 0x5c, 0x6c, 0x01, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x42, 0xf2, 0x5c, 0xdc, 0x45, - 0xa9, 0x39, 0x89, 0x95, 0xa9, 0x45, 0xf1, 0x69, 0xa9, 0xa9, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0x2c, - 0x41, 0x5c, 0x50, 0x21, 0xb7, 0xd4, 0x54, 0x27, 0xa7, 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, 0x48, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85, 0x9a, - 0x0e, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0xc0, 0xae, 0x2e, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, - 0x62, 0x03, 0xdb, 0x6a, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xfa, 0x4c, 0xfd, 0xd0, 0x00, - 0x00, 0x00, +var fileDescriptor_d7b94a7254cf916a = []byte{ + // 187 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, + 0x44, 0xe2, 0xe9, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x89, 0x40, 0x94, 0xe9, 0x21, 0x49, 0x94, + 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x92, + 0x10, 0xb5, 0xf1, 0x10, 0x09, 0xa8, 0x46, 0x30, 0x47, 0x49, 0x93, 0x8b, 0x2d, 0x20, 0xb1, 0x28, + 0x31, 0xb7, 0x58, 0x48, 0x9e, 0x8b, 0xbb, 0x28, 0x35, 0x27, 0xb1, 0x32, 0xb5, 0x28, 0x3e, 0x2d, + 0x35, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x25, 0x88, 0x0b, 0x2a, 0xe4, 0x96, 0x9a, 0xea, 0xe4, + 0x79, 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, 0xfa, 0xe9, 0x99, 0x25, 0x19, + 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x30, 0xd7, 0x83, 0x29, 0xdd, 0xe2, 0x94, 0x6c, 0xfd, + 0x0a, 0x64, 0xaf, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x2d, 0x37, 0x06, 0x04, 0x00, + 0x00, 0xff, 0xff, 0xd1, 0xfd, 0x76, 0x86, 0xec, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -112,15 +114,15 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { var l int _ = l if m.RelayerFee != 0 { - i = encodeVarintIbc(dAtA, i, uint64(m.RelayerFee)) + i = encodeVarintCrosschain(dAtA, i, uint64(m.RelayerFee)) i-- dAtA[i] = 0x8 } return len(dAtA) - i, nil } -func encodeVarintIbc(dAtA []byte, offset int, v uint64) int { - offset -= sovIbc(v) +func encodeVarintCrosschain(dAtA []byte, offset int, v uint64) int { + offset -= sovCrosschain(v) base := offset for v >= 1<<7 { dAtA[offset] = uint8(v&0x7f | 0x80) @@ -137,16 +139,16 @@ func (m *Params) Size() (n int) { var l int _ = l if m.RelayerFee != 0 { - n += 1 + sovIbc(uint64(m.RelayerFee)) + n += 1 + sovCrosschain(uint64(m.RelayerFee)) } return n } -func sovIbc(x uint64) (n int) { +func sovCrosschain(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 } -func sozIbc(x uint64) (n int) { - return sovIbc(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +func sozCrosschain(x uint64) (n int) { + return sovCrosschain(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } func (m *Params) Unmarshal(dAtA []byte) error { l := len(dAtA) @@ -156,7 +158,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { - return ErrIntOverflowIbc + return ErrIntOverflowCrosschain } if iNdEx >= l { return io.ErrUnexpectedEOF @@ -184,7 +186,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { m.RelayerFee = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { - return ErrIntOverflowIbc + return ErrIntOverflowCrosschain } if iNdEx >= l { return io.ErrUnexpectedEOF @@ -198,12 +200,12 @@ func (m *Params) Unmarshal(dAtA []byte) error { } default: iNdEx = preIndex - skippy, err := skipIbc(dAtA[iNdEx:]) + skippy, err := skipCrosschain(dAtA[iNdEx:]) if err != nil { return err } if (skippy < 0) || (iNdEx+skippy) < 0 { - return ErrInvalidLengthIbc + return ErrInvalidLengthCrosschain } if (iNdEx + skippy) > l { return io.ErrUnexpectedEOF @@ -217,7 +219,7 @@ func (m *Params) Unmarshal(dAtA []byte) error { } return nil } -func skipIbc(dAtA []byte) (n int, err error) { +func skipCrosschain(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 depth := 0 @@ -225,7 +227,7 @@ func skipIbc(dAtA []byte) (n int, err error) { var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { - return 0, ErrIntOverflowIbc + return 0, ErrIntOverflowCrosschain } if iNdEx >= l { return 0, io.ErrUnexpectedEOF @@ -242,7 +244,7 @@ func skipIbc(dAtA []byte) (n int, err error) { case 0: for shift := uint(0); ; shift += 7 { if shift >= 64 { - return 0, ErrIntOverflowIbc + return 0, ErrIntOverflowCrosschain } if iNdEx >= l { return 0, io.ErrUnexpectedEOF @@ -258,7 +260,7 @@ func skipIbc(dAtA []byte) (n int, err error) { var length int for shift := uint(0); ; shift += 7 { if shift >= 64 { - return 0, ErrIntOverflowIbc + return 0, ErrIntOverflowCrosschain } if iNdEx >= l { return 0, io.ErrUnexpectedEOF @@ -271,14 +273,14 @@ func skipIbc(dAtA []byte) (n int, err error) { } } if length < 0 { - return 0, ErrInvalidLengthIbc + return 0, ErrInvalidLengthCrosschain } iNdEx += length case 3: depth++ case 4: if depth == 0 { - return 0, ErrUnexpectedEndOfGroupIbc + return 0, ErrUnexpectedEndOfGroupCrosschain } depth-- case 5: @@ -287,7 +289,7 @@ func skipIbc(dAtA []byte) (n int, err error) { return 0, fmt.Errorf("proto: illegal wireType %d", wireType) } if iNdEx < 0 { - return 0, ErrInvalidLengthIbc + return 0, ErrInvalidLengthCrosschain } if depth == 0 { return iNdEx, nil @@ -297,7 +299,7 @@ func skipIbc(dAtA []byte) (n int, err error) { } var ( - ErrInvalidLengthIbc = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowIbc = fmt.Errorf("proto: integer overflow") - ErrUnexpectedEndOfGroupIbc = fmt.Errorf("proto: unexpected end of group") + ErrInvalidLengthCrosschain = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowCrosschain = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupCrosschain = fmt.Errorf("proto: unexpected end of group") ) diff --git a/x/ibc/types/event.pb.go b/x/crosschain/types/event.pb.go similarity index 72% rename from x/ibc/types/event.pb.go rename to x/crosschain/types/event.pb.go index 71422e3c6e..b8592900e6 100644 --- a/x/ibc/types/event.pb.go +++ b/x/crosschain/types/event.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/ibc/v1/event.proto +// source: cosmos/crosschain/v1/event.proto package types @@ -23,7 +23,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -type EventIBCPackage struct { +type EventCrossChainPackage struct { SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` @@ -34,18 +34,18 @@ type EventIBCPackage struct { RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` } -func (m *EventIBCPackage) Reset() { *m = EventIBCPackage{} } -func (m *EventIBCPackage) String() string { return proto.CompactTextString(m) } -func (*EventIBCPackage) ProtoMessage() {} -func (*EventIBCPackage) Descriptor() ([]byte, []int) { - return fileDescriptor_910737647fd17fb9, []int{0} +func (m *EventCrossChainPackage) Reset() { *m = EventCrossChainPackage{} } +func (m *EventCrossChainPackage) String() string { return proto.CompactTextString(m) } +func (*EventCrossChainPackage) ProtoMessage() {} +func (*EventCrossChainPackage) Descriptor() ([]byte, []int) { + return fileDescriptor_2a5a3ba75f5dd2c3, []int{0} } -func (m *EventIBCPackage) XXX_Unmarshal(b []byte) error { +func (m *EventCrossChainPackage) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *EventIBCPackage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *EventCrossChainPackage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_EventIBCPackage.Marshal(b, m, deterministic) + return xxx_messageInfo_EventCrossChainPackage.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -55,68 +55,68 @@ func (m *EventIBCPackage) XXX_Marshal(b []byte, deterministic bool) ([]byte, err return b[:n], nil } } -func (m *EventIBCPackage) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventIBCPackage.Merge(m, src) +func (m *EventCrossChainPackage) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventCrossChainPackage.Merge(m, src) } -func (m *EventIBCPackage) XXX_Size() int { +func (m *EventCrossChainPackage) XXX_Size() int { return m.Size() } -func (m *EventIBCPackage) XXX_DiscardUnknown() { - xxx_messageInfo_EventIBCPackage.DiscardUnknown(m) +func (m *EventCrossChainPackage) XXX_DiscardUnknown() { + xxx_messageInfo_EventCrossChainPackage.DiscardUnknown(m) } -var xxx_messageInfo_EventIBCPackage proto.InternalMessageInfo +var xxx_messageInfo_EventCrossChainPackage proto.InternalMessageInfo -func (m *EventIBCPackage) GetSrcChainId() uint32 { +func (m *EventCrossChainPackage) GetSrcChainId() uint32 { if m != nil { return m.SrcChainId } return 0 } -func (m *EventIBCPackage) GetDestChainId() uint32 { +func (m *EventCrossChainPackage) GetDestChainId() uint32 { if m != nil { return m.DestChainId } return 0 } -func (m *EventIBCPackage) GetChannelId() uint32 { +func (m *EventCrossChainPackage) GetChannelId() uint32 { if m != nil { return m.ChannelId } return 0 } -func (m *EventIBCPackage) GetSequence() uint64 { +func (m *EventCrossChainPackage) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } -func (m *EventIBCPackage) GetPackageType() uint32 { +func (m *EventCrossChainPackage) GetPackageType() uint32 { if m != nil { return m.PackageType } return 0 } -func (m *EventIBCPackage) GetTimestamp() uint64 { +func (m *EventCrossChainPackage) GetTimestamp() uint64 { if m != nil { return m.Timestamp } return 0 } -func (m *EventIBCPackage) GetPackageLoad() []byte { +func (m *EventCrossChainPackage) GetPackageLoad() []byte { if m != nil { return m.PackageLoad } return nil } -func (m *EventIBCPackage) GetRelayerFee() string { +func (m *EventCrossChainPackage) GetRelayerFee() string { if m != nil { return m.RelayerFee } @@ -124,37 +124,37 @@ func (m *EventIBCPackage) GetRelayerFee() string { } func init() { - proto.RegisterType((*EventIBCPackage)(nil), "cosmos.authz.v1beta1.EventIBCPackage") + proto.RegisterType((*EventCrossChainPackage)(nil), "cosmos.crosschain.v1.EventCrossChainPackage") } -func init() { proto.RegisterFile("cosmos/ibc/v1/event.proto", fileDescriptor_910737647fd17fb9) } +func init() { proto.RegisterFile("cosmos/crosschain/v1/event.proto", fileDescriptor_2a5a3ba75f5dd2c3) } -var fileDescriptor_910737647fd17fb9 = []byte{ +var fileDescriptor_2a5a3ba75f5dd2c3 = []byte{ // 323 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x41, 0x4f, 0xc2, 0x30, - 0x14, 0xc7, 0x29, 0x22, 0x42, 0x81, 0x98, 0x34, 0x1e, 0x26, 0xd1, 0x3a, 0x39, 0xed, 0xe2, 0x16, - 0xe2, 0x37, 0x80, 0x68, 0x42, 0xe2, 0xc1, 0x10, 0x4f, 0x5e, 0x96, 0xae, 0x7d, 0xb2, 0x05, 0xb6, - 0xce, 0xb5, 0x10, 0xf1, 0x53, 0x78, 0xf3, 0x2b, 0x79, 0xe4, 0xe8, 0xd1, 0xc0, 0x17, 0x31, 0xeb, - 0x2a, 0x78, 0x6a, 0xde, 0xaf, 0xbf, 0xf7, 0xcf, 0xcb, 0x7b, 0xf8, 0x9c, 0x4b, 0x95, 0x4a, 0x15, - 0x24, 0x11, 0x0f, 0x56, 0xc3, 0x00, 0x56, 0x90, 0x69, 0x3f, 0x2f, 0xa4, 0x96, 0xe4, 0xac, 0xfa, - 0xf2, 0xd9, 0x52, 0xc7, 0xef, 0xfe, 0x6a, 0x18, 0x81, 0x66, 0xc3, 0xbe, 0x6d, 0x08, 0x8d, 0x13, - 0x58, 0xc5, 0x14, 0x83, 0xcf, 0x3a, 0x3e, 0xbd, 0x2b, 0x03, 0x26, 0xa3, 0xf1, 0x23, 0xe3, 0x73, - 0x36, 0x03, 0xe2, 0xe2, 0xae, 0x2a, 0x78, 0xc8, 0x63, 0x96, 0x64, 0x61, 0x22, 0x1c, 0xe4, 0x22, - 0xaf, 0x37, 0xc5, 0xaa, 0xe0, 0xe3, 0x12, 0x4d, 0x04, 0x19, 0xe0, 0x9e, 0x00, 0xa5, 0x0f, 0x4a, - 0xdd, 0x28, 0x9d, 0x12, 0xfe, 0x39, 0x97, 0x18, 0xf3, 0x98, 0x65, 0x19, 0x2c, 0x4a, 0xe1, 0xc8, - 0x08, 0x6d, 0x4b, 0x26, 0x82, 0xf4, 0x71, 0x4b, 0xc1, 0xeb, 0x12, 0x32, 0x0e, 0x4e, 0xc3, 0x45, - 0x5e, 0x63, 0xba, 0xaf, 0xc9, 0x35, 0xee, 0xe6, 0xd5, 0x2c, 0xa1, 0x5e, 0xe7, 0xe0, 0x1c, 0x57, - 0xe9, 0x96, 0x3d, 0xad, 0x73, 0x20, 0x17, 0xb8, 0xad, 0x93, 0x14, 0x94, 0x66, 0x69, 0xee, 0x34, - 0x4d, 0xff, 0x01, 0xfc, 0x0f, 0x58, 0x48, 0x26, 0x9c, 0x13, 0x17, 0x79, 0xdd, 0x7d, 0xc0, 0x83, - 0x64, 0x82, 0x5c, 0xe1, 0x4e, 0x01, 0x0b, 0xb6, 0x86, 0x22, 0x7c, 0x01, 0x70, 0x5a, 0x2e, 0xf2, - 0xda, 0x53, 0x6c, 0xd1, 0x3d, 0xc0, 0x68, 0xf4, 0xb5, 0xa5, 0x68, 0xb3, 0xa5, 0xe8, 0x67, 0x4b, - 0xd1, 0xc7, 0x8e, 0xd6, 0x36, 0x3b, 0x5a, 0xfb, 0xde, 0xd1, 0xda, 0xb3, 0x37, 0x4b, 0x74, 0xbc, - 0x8c, 0x7c, 0x2e, 0x53, 0xbb, 0x4c, 0xfb, 0xdc, 0x28, 0x31, 0x0f, 0xde, 0xcc, 0x5d, 0xca, 0xb9, - 0x55, 0xd4, 0x34, 0x4b, 0xbe, 0xfd, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x74, 0xd6, 0x36, 0x01, 0xb2, + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x4f, 0x4e, 0xc2, 0x40, + 0x14, 0xc6, 0x19, 0x44, 0x84, 0x07, 0x6c, 0x26, 0xc6, 0x54, 0xa2, 0xb5, 0xb2, 0xea, 0xc6, 0x4e, + 0x88, 0x37, 0x90, 0x68, 0x42, 0xe2, 0xc2, 0x10, 0x57, 0x6e, 0x9a, 0x61, 0xe6, 0x09, 0x0d, 0xb4, + 0x53, 0x3b, 0x03, 0x91, 0x5b, 0x78, 0x02, 0xcf, 0xe3, 0x92, 0xa5, 0x4b, 0x03, 0x17, 0x31, 0x9d, + 0x96, 0x3f, 0xab, 0xc9, 0xfb, 0xe5, 0xf7, 0x7d, 0x79, 0x99, 0x07, 0x9e, 0x50, 0x3a, 0x56, 0x9a, + 0x89, 0x4c, 0x69, 0x2d, 0xa6, 0x3c, 0x4a, 0xd8, 0xb2, 0xcf, 0x70, 0x89, 0x89, 0x09, 0xd2, 0x4c, + 0x19, 0x45, 0xcf, 0x0b, 0x23, 0x38, 0x18, 0xc1, 0xb2, 0xdf, 0xbd, 0x2c, 0x68, 0x68, 0x1d, 0x56, + 0x2a, 0x76, 0xe8, 0x7d, 0x57, 0xe1, 0xe2, 0x31, 0x2f, 0x18, 0xe4, 0x89, 0x41, 0x9e, 0x78, 0xe1, + 0x62, 0xc6, 0x27, 0x48, 0x3d, 0x68, 0xeb, 0x4c, 0x84, 0xb6, 0x25, 0x8c, 0xa4, 0x43, 0x3c, 0xe2, + 0x77, 0x46, 0xa0, 0x33, 0x61, 0xb5, 0xa1, 0xa4, 0x3d, 0xe8, 0x48, 0xd4, 0xe6, 0xa0, 0x54, 0xad, + 0xd2, 0xca, 0xe1, 0xce, 0xb9, 0x06, 0x10, 0x53, 0x9e, 0x24, 0x38, 0xcf, 0x85, 0x13, 0x2b, 0x34, + 0x4b, 0x32, 0x94, 0xb4, 0x0b, 0x0d, 0x8d, 0x1f, 0x0b, 0x4c, 0x04, 0x3a, 0x35, 0x8f, 0xf8, 0xb5, + 0xd1, 0x7e, 0xa6, 0xb7, 0xd0, 0x4e, 0x8b, 0x5d, 0x42, 0xb3, 0x4a, 0xd1, 0x39, 0x2d, 0xda, 0x4b, + 0xf6, 0xba, 0x4a, 0x91, 0x5e, 0x41, 0xd3, 0x44, 0x31, 0x6a, 0xc3, 0xe3, 0xd4, 0xa9, 0xdb, 0xfc, + 0x01, 0x1c, 0x17, 0xcc, 0x15, 0x97, 0xce, 0x99, 0x47, 0xfc, 0xf6, 0xbe, 0xe0, 0x59, 0x71, 0x49, + 0x6f, 0xa0, 0x95, 0xe1, 0x9c, 0xaf, 0x30, 0x0b, 0xdf, 0x11, 0x9d, 0x86, 0x47, 0xfc, 0xe6, 0x08, + 0x4a, 0xf4, 0x84, 0xf8, 0x30, 0xfc, 0xd9, 0xb8, 0x64, 0xbd, 0x71, 0xc9, 0xdf, 0xc6, 0x25, 0x5f, + 0x5b, 0xb7, 0xb2, 0xde, 0xba, 0x95, 0xdf, 0xad, 0x5b, 0x79, 0x63, 0x93, 0xc8, 0x4c, 0x17, 0xe3, + 0x40, 0xa8, 0x98, 0xed, 0x0e, 0x63, 0x9f, 0x3b, 0x2d, 0x67, 0xec, 0xf3, 0xf8, 0x4a, 0xf9, 0xfa, + 0x7a, 0x5c, 0xb7, 0x5f, 0x7e, 0xff, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x48, 0xe7, 0x4a, 0x77, 0xc7, 0x01, 0x00, 0x00, } -func (m *EventIBCPackage) Marshal() (dAtA []byte, err error) { +func (m *EventCrossChainPackage) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -164,12 +164,12 @@ func (m *EventIBCPackage) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *EventIBCPackage) MarshalTo(dAtA []byte) (int, error) { +func (m *EventCrossChainPackage) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *EventIBCPackage) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EventCrossChainPackage) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -232,7 +232,7 @@ func encodeVarintEvent(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *EventIBCPackage) Size() (n int) { +func (m *EventCrossChainPackage) Size() (n int) { if m == nil { return 0 } @@ -273,7 +273,7 @@ func sovEvent(x uint64) (n int) { func sozEvent(x uint64) (n int) { return sovEvent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (m *EventIBCPackage) Unmarshal(dAtA []byte) error { +func (m *EventCrossChainPackage) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -296,10 +296,10 @@ func (m *EventIBCPackage) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: EventIBCPackage: wiretype end group for non-group") + return fmt.Errorf("proto: EventCrossChainPackage: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: EventIBCPackage: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EventCrossChainPackage: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: diff --git a/x/ibc/types/expected_keepers.go b/x/crosschain/types/expected_keepers.go similarity index 100% rename from x/ibc/types/expected_keepers.go rename to x/crosschain/types/expected_keepers.go diff --git a/x/ibc/types/keys.go b/x/crosschain/types/keys.go similarity index 100% rename from x/ibc/types/keys.go rename to x/crosschain/types/keys.go diff --git a/x/ibc/types/params.go b/x/crosschain/types/params.go similarity index 100% rename from x/ibc/types/params.go rename to x/crosschain/types/params.go diff --git a/x/ibc/types/query.pb.go b/x/crosschain/types/query.pb.go similarity index 83% rename from x/ibc/types/query.pb.go rename to x/crosschain/types/query.pb.go index c63c8a9dbc..0f216dc8e9 100644 --- a/x/ibc/types/query.pb.go +++ b/x/crosschain/types/query.pb.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-gogo. DO NOT EDIT. -// source: cosmos/ibc/v1/query.proto +// source: cosmos/crosschain/v1/query.proto package types @@ -37,7 +37,7 @@ func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } func (*QueryParamsRequest) ProtoMessage() {} func (*QueryParamsRequest) Descriptor() ([]byte, []int) { - return fileDescriptor_0ec2ac3c289eec95, []int{0} + return fileDescriptor_3c0bc65cbea0cca3, []int{0} } func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -76,7 +76,7 @@ func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } func (*QueryParamsResponse) ProtoMessage() {} func (*QueryParamsResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_0ec2ac3c289eec95, []int{1} + return fileDescriptor_3c0bc65cbea0cca3, []int{1} } func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -113,32 +113,32 @@ func (m *QueryParamsResponse) GetParams() Params { } func init() { - proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.ibc.v1.QueryParamsRequest") - proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.ibc.v1.QueryParamsResponse") -} - -func init() { proto.RegisterFile("cosmos/ibc/v1/query.proto", fileDescriptor_0ec2ac3c289eec95) } - -var fileDescriptor_0ec2ac3c289eec95 = []byte{ - // 273 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0xcf, 0x4c, 0x4a, 0xd6, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, - 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x85, 0x48, 0xe9, 0x65, 0x26, 0x25, 0xeb, 0x95, 0x19, - 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x65, 0xf4, 0x41, 0x2c, 0x88, 0x22, 0x29, 0x99, 0xf4, - 0xfc, 0xfc, 0xf4, 0x9c, 0x54, 0xfd, 0xc4, 0x82, 0x4c, 0xfd, 0xc4, 0xbc, 0xbc, 0xfc, 0x92, 0xc4, - 0x92, 0xcc, 0xfc, 0xbc, 0x62, 0xa8, 0xac, 0x38, 0xaa, 0xe9, 0x20, 0x93, 0xc0, 0x12, 0x4a, 0x22, - 0x5c, 0x42, 0x81, 0x20, 0xab, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x83, 0x52, 0x0b, 0x4b, 0x53, - 0x8b, 0x4b, 0x94, 0xbc, 0xb8, 0x84, 0x51, 0x44, 0x8b, 0x0b, 0xf2, 0xf3, 0x8a, 0x53, 0x85, 0x8c, - 0xb9, 0xd8, 0x0a, 0xc0, 0x22, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0xa2, 0x7a, 0x28, 0x2e, - 0xd3, 0x83, 0x28, 0x77, 0x62, 0x39, 0x71, 0x4f, 0x9e, 0x21, 0x08, 0xaa, 0xd4, 0xa8, 0x9c, 0x8b, - 0x15, 0x6c, 0x96, 0x50, 0x1e, 0x17, 0x1b, 0x44, 0x81, 0x90, 0x22, 0x9a, 0x3e, 0x4c, 0x17, 0x48, - 0x29, 0xe1, 0x53, 0x02, 0x71, 0x8e, 0x92, 0x6c, 0xd3, 0xe5, 0x27, 0x93, 0x99, 0xc4, 0x85, 0x44, - 0xf5, 0x51, 0x7d, 0x07, 0xb1, 0xd8, 0xc9, 0xe9, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, - 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, - 0x18, 0xa2, 0x34, 0xd2, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0x61, 0x5a, 0x21, - 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, 0x05, 0xd8, 0x9c, 0x92, 0xca, 0x82, 0xd4, 0xe2, 0x24, 0x36, - 0x70, 0x28, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xd8, 0x19, 0x86, 0x24, 0x9e, 0x01, 0x00, - 0x00, + proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.crosschain.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.crosschain.v1.QueryParamsResponse") +} + +func init() { proto.RegisterFile("cosmos/crosschain/v1/query.proto", fileDescriptor_3c0bc65cbea0cca3) } + +var fileDescriptor_3c0bc65cbea0cca3 = []byte{ + // 283 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, + 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xa8, + 0xd0, 0x43, 0xa8, 0xd0, 0x2b, 0x33, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, 0xd0, 0x07, + 0xb1, 0x20, 0x6a, 0xa5, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, 0x0b, 0x32, 0xf5, + 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xa1, 0xb2, 0xaa, 0x58, 0xed, + 0x42, 0x32, 0x17, 0xac, 0x4c, 0x49, 0x84, 0x4b, 0x28, 0x10, 0x64, 0x7f, 0x40, 0x62, 0x51, 0x62, + 0x6e, 0x71, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x52, 0x20, 0x97, 0x30, 0x8a, 0x68, 0x71, + 0x41, 0x7e, 0x5e, 0x71, 0xaa, 0x90, 0x15, 0x17, 0x5b, 0x01, 0x58, 0x44, 0x82, 0x51, 0x81, 0x51, + 0x83, 0xdb, 0x48, 0x46, 0x0f, 0x9b, 0x73, 0xf5, 0x20, 0xba, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, + 0x08, 0x82, 0xea, 0x30, 0xea, 0x65, 0xe4, 0x62, 0x05, 0x9b, 0x29, 0xd4, 0xcc, 0xc8, 0xc5, 0x06, + 0x51, 0x22, 0xa4, 0x81, 0xdd, 0x00, 0x4c, 0x17, 0x49, 0x69, 0x12, 0xa1, 0x12, 0xe2, 0x4a, 0x25, + 0x95, 0xa6, 0xcb, 0x4f, 0x26, 0x33, 0xc9, 0x09, 0xc9, 0xe8, 0x63, 0x0d, 0x02, 0x88, 0x7b, 0x9c, + 0x3c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, + 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3f, 0x3d, 0xb3, 0x24, + 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x17, 0x6e, 0x02, 0x98, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, + 0x40, 0x36, 0xae, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x94, 0xc6, 0x80, 0x00, 0x00, + 0x00, 0xff, 0xff, 0xe8, 0x38, 0x15, 0x95, 0xdf, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -167,7 +167,7 @@ func NewQueryClient(cc grpc1.ClientConn) QueryClient { func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { out := new(QueryParamsResponse) - err := c.cc.Invoke(ctx, "/cosmos.ibc.v1.Query/Params", in, out, opts...) + err := c.cc.Invoke(ctx, "/cosmos.crosschain.v1.Query/Params", in, out, opts...) if err != nil { return nil, err } @@ -202,7 +202,7 @@ func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interf } info := &grpc.UnaryServerInfo{ Server: srv, - FullMethod: "/cosmos.ibc.v1.Query/Params", + FullMethod: "/cosmos.crosschain.v1.Query/Params", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) @@ -211,7 +211,7 @@ func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interf } var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.ibc.v1.Query", + ServiceName: "cosmos.crosschain.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{ { @@ -220,7 +220,7 @@ var _Query_serviceDesc = grpc.ServiceDesc{ }, }, Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/ibc/v1/query.proto", + Metadata: "cosmos/crosschain/v1/query.proto", } func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { diff --git a/x/ibc/types/query.pb.gw.go b/x/crosschain/types/query.pb.gw.go similarity index 97% rename from x/ibc/types/query.pb.gw.go rename to x/crosschain/types/query.pb.gw.go index 7f2a67f5b4..331a372259 100644 --- a/x/ibc/types/query.pb.gw.go +++ b/x/crosschain/types/query.pb.gw.go @@ -1,5 +1,5 @@ // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. -// source: cosmos/ibc/v1/query.proto +// source: cosmos/crosschain/v1/query.proto /* Package types is a reverse proxy. @@ -145,7 +145,7 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie } var ( - pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "ibc", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "crosschain", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( From 694989a7fa9a09cc082c9b50e1e6880a2cad6900 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 15 Nov 2022 15:59:14 +0800 Subject: [PATCH 04/50] minor changes --- x/crosschain/module.go | 2 +- x/crosschain/types/keys.go | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/x/crosschain/module.go b/x/crosschain/module.go index 7524e8f0db..5dc0501a91 100644 --- a/x/crosschain/module.go +++ b/x/crosschain/module.go @@ -1,4 +1,4 @@ -package params +package crosschain import ( "context" diff --git a/x/crosschain/types/keys.go b/x/crosschain/types/keys.go index 060770a641..0b40defaa6 100644 --- a/x/crosschain/types/keys.go +++ b/x/crosschain/types/keys.go @@ -8,7 +8,7 @@ import ( ) const ( - ModuleName = "ibc" + ModuleName = "crosschain" StoreKey = ModuleName QuerierRoute = StoreKey @@ -50,14 +50,14 @@ func BuildIBCPackageKey(srcChainID, destChainID sdk.ChainID, channelID sdk.Chann } type ChannelPermissionSetting struct { - SideChainId string `json:"side_chain_id"` + DestChainId string `json:"dest_chain_id"` ChannelId sdk.ChannelID `json:"channel_id"` Permission sdk.ChannelPermission `json:"permission"` } func (c *ChannelPermissionSetting) Check() error { - if len(c.SideChainId) == 0 || len(c.SideChainId) > MaxSideChainIdLength { - return fmt.Errorf("invalid side chain id") + if len(c.DestChainId) == 0 || len(c.DestChainId) > MaxSideChainIdLength { + return fmt.Errorf("invalid dest chain id") } if c.ChannelId == GovChannelId { return fmt.Errorf("gov channel id is forbidden to set") From d5510c8f02a177d829c253545d26c13e9d4f410d Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 23 Nov 2022 10:05:38 +0800 Subject: [PATCH 05/50] add oracle module --- bsc/rlp/decode.go | 989 +++++++++++++++++++++++++ bsc/rlp/decode_tail_test.go | 49 ++ bsc/rlp/decode_test.go | 929 +++++++++++++++++++++++ bsc/rlp/doc.go | 130 ++++ bsc/rlp/encode.go | 612 +++++++++++++++ bsc/rlp/encode_test.go | 402 ++++++++++ bsc/rlp/encoder_example_test.go | 46 ++ bsc/rlp/raw.go | 156 ++++ bsc/rlp/raw_test.go | 196 +++++ bsc/rlp/typecache.go | 215 ++++++ proto/cosmos/oracle/v1/event.proto | 18 + proto/cosmos/oracle/v1/query.proto | 12 + proto/cosmos/oracle/v1/tx.proto | 32 + types/cross_chain.go | 19 +- types/tokens.go | 7 + x/crosschain/keeper/keeper.go | 4 + x/crosschain/types/expected_keepers.go | 10 - x/oracle/README.md | 6 + x/oracle/keeper/keeper.go | 92 +++ x/oracle/keeper/msg_server.go | 183 +++++ x/oracle/keeper/querier.go | 18 + x/oracle/metrics/metrics.go | 31 + x/oracle/module.go | 132 ++++ x/oracle/types/codec.go | 8 + x/oracle/types/errors.go | 17 + x/oracle/types/event.pb.go | 577 +++++++++++++++ x/oracle/types/expected_keepers.go | 22 + x/oracle/types/keys.go | 12 + x/oracle/types/msgs.go | 96 +++ x/oracle/types/msgs_test.go | 21 + x/oracle/types/query.pb.go | 87 +++ x/oracle/types/tx.pb.go | 803 ++++++++++++++++++++ x/oracle/types/types.go | 1 + 33 files changed, 5920 insertions(+), 12 deletions(-) create mode 100644 bsc/rlp/decode.go create mode 100644 bsc/rlp/decode_tail_test.go create mode 100644 bsc/rlp/decode_test.go create mode 100644 bsc/rlp/doc.go create mode 100644 bsc/rlp/encode.go create mode 100644 bsc/rlp/encode_test.go create mode 100644 bsc/rlp/encoder_example_test.go create mode 100644 bsc/rlp/raw.go create mode 100644 bsc/rlp/raw_test.go create mode 100644 bsc/rlp/typecache.go create mode 100644 proto/cosmos/oracle/v1/event.proto create mode 100644 proto/cosmos/oracle/v1/query.proto create mode 100644 proto/cosmos/oracle/v1/tx.proto create mode 100644 types/tokens.go delete mode 100644 x/crosschain/types/expected_keepers.go create mode 100644 x/oracle/README.md create mode 100644 x/oracle/keeper/keeper.go create mode 100644 x/oracle/keeper/msg_server.go create mode 100644 x/oracle/keeper/querier.go create mode 100644 x/oracle/metrics/metrics.go create mode 100644 x/oracle/module.go create mode 100644 x/oracle/types/codec.go create mode 100644 x/oracle/types/errors.go create mode 100644 x/oracle/types/event.pb.go create mode 100644 x/oracle/types/expected_keepers.go create mode 100644 x/oracle/types/keys.go create mode 100644 x/oracle/types/msgs.go create mode 100644 x/oracle/types/msgs_test.go create mode 100644 x/oracle/types/query.pb.go create mode 100644 x/oracle/types/tx.pb.go create mode 100644 x/oracle/types/types.go diff --git a/bsc/rlp/decode.go b/bsc/rlp/decode.go new file mode 100644 index 0000000000..5f3f5eedfd --- /dev/null +++ b/bsc/rlp/decode.go @@ -0,0 +1,989 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "bufio" + "bytes" + "encoding/binary" + "errors" + "fmt" + "io" + "math/big" + "reflect" + "strings" + "sync" +) + +//lint:ignore ST1012 EOL is not an error. + +// EOL is returned when the end of the current list +// has been reached during streaming. +var EOL = errors.New("rlp: end of list") + +var ( + ErrExpectedString = errors.New("rlp: expected String or Byte") + ErrExpectedList = errors.New("rlp: expected List") + ErrCanonInt = errors.New("rlp: non-canonical integer format") + ErrCanonSize = errors.New("rlp: non-canonical size information") + ErrElemTooLarge = errors.New("rlp: element is larger than containing list") + ErrValueTooLarge = errors.New("rlp: value size exceeds available input length") + ErrMoreThanOneValue = errors.New("rlp: input contains more than one value") + + // internal errors + errNotInList = errors.New("rlp: call of ListEnd outside of any list") + errNotAtEOL = errors.New("rlp: call of ListEnd not positioned at EOL") + errUintOverflow = errors.New("rlp: uint overflow") + errNoPointer = errors.New("rlp: interface given to Decode must be a pointer") + errDecodeIntoNil = errors.New("rlp: pointer given to Decode must not be nil") + + streamPool = sync.Pool{ + New: func() interface{} { return new(Stream) }, + } +) + +// Decoder is implemented by types that require custom RLP decoding rules or need to decode +// into private fields. +// +// The DecodeRLP method should read one value from the given Stream. It is not forbidden to +// read less or more, but it might be confusing. +type Decoder interface { + DecodeRLP(*Stream) error +} + +// Decode parses RLP-encoded data from r and stores the result in the value pointed to by +// val. Please see package-level documentation for the decoding rules. Val must be a +// non-nil pointer. +// +// If r does not implement ByteReader, Decode will do its own buffering. +// +// Note that Decode does not set an input limit for all readers and may be vulnerable to +// panics cause by huge value sizes. If you need an input limit, use +// +// NewStream(r, limit).Decode(val) +func Decode(r io.Reader, val interface{}) error { + stream := streamPool.Get().(*Stream) + defer streamPool.Put(stream) + + stream.Reset(r, 0) + return stream.Decode(val) +} + +// DecodeBytes parses RLP data from b into val. Please see package-level documentation for +// the decoding rules. The input must contain exactly one value and no trailing data. +func DecodeBytes(b []byte, val interface{}) error { + r := bytes.NewReader(b) + + stream := streamPool.Get().(*Stream) + defer streamPool.Put(stream) + + stream.Reset(r, uint64(len(b))) + if err := stream.Decode(val); err != nil { + return err + } + if r.Len() > 0 { + return ErrMoreThanOneValue + } + return nil +} + +type decodeError struct { + msg string + typ reflect.Type + ctx []string +} + +func (err *decodeError) Error() string { + ctx := "" + if len(err.ctx) > 0 { + ctx = ", decoding into " + for i := len(err.ctx) - 1; i >= 0; i-- { + ctx += err.ctx[i] + } + } + return fmt.Sprintf("rlp: %s for %v%s", err.msg, err.typ, ctx) +} + +func wrapStreamError(err error, typ reflect.Type) error { + switch err { + case ErrCanonInt: + return &decodeError{msg: "non-canonical integer (leading zero bytes)", typ: typ} + case ErrCanonSize: + return &decodeError{msg: "non-canonical size information", typ: typ} + case ErrExpectedList: + return &decodeError{msg: "expected input list", typ: typ} + case ErrExpectedString: + return &decodeError{msg: "expected input string or byte", typ: typ} + case errUintOverflow: + return &decodeError{msg: "input string too long", typ: typ} + case errNotAtEOL: + return &decodeError{msg: "input list has too many elements", typ: typ} + } + return err +} + +func addErrorContext(err error, ctx string) error { + if decErr, ok := err.(*decodeError); ok { + decErr.ctx = append(decErr.ctx, ctx) + } + return err +} + +var ( + decoderInterface = reflect.TypeOf(new(Decoder)).Elem() + bigInt = reflect.TypeOf(big.Int{}) +) + +func makeDecoder(typ reflect.Type, tags tags) (dec decoder, err error) { + kind := typ.Kind() + switch { + case typ == rawValueType: + return decodeRawValue, nil + case typ.AssignableTo(reflect.PtrTo(bigInt)): + return decodeBigInt, nil + case typ.AssignableTo(bigInt): + return decodeBigIntNoPtr, nil + case kind == reflect.Ptr: + return makePtrDecoder(typ, tags) + case reflect.PtrTo(typ).Implements(decoderInterface): + return decodeDecoder, nil + case isUint(kind): + return decodeUint, nil + case kind == reflect.Bool: + return decodeBool, nil + case kind == reflect.String: + return decodeString, nil + case kind == reflect.Slice || kind == reflect.Array: + return makeListDecoder(typ, tags) + case kind == reflect.Struct: + return makeStructDecoder(typ) + case kind == reflect.Interface: + return decodeInterface, nil + default: + return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) + } +} + +func decodeRawValue(s *Stream, val reflect.Value) error { + r, err := s.Raw() + if err != nil { + return err + } + val.SetBytes(r) + return nil +} + +func decodeUint(s *Stream, val reflect.Value) error { + typ := val.Type() + num, err := s.uint(typ.Bits()) + if err != nil { + return wrapStreamError(err, val.Type()) + } + val.SetUint(num) + return nil +} + +func decodeBool(s *Stream, val reflect.Value) error { + b, err := s.Bool() + if err != nil { + return wrapStreamError(err, val.Type()) + } + val.SetBool(b) + return nil +} + +func decodeString(s *Stream, val reflect.Value) error { + b, err := s.Bytes() + if err != nil { + return wrapStreamError(err, val.Type()) + } + val.SetString(string(b)) + return nil +} + +func decodeBigIntNoPtr(s *Stream, val reflect.Value) error { + return decodeBigInt(s, val.Addr()) +} + +func decodeBigInt(s *Stream, val reflect.Value) error { + b, err := s.Bytes() + if err != nil { + return wrapStreamError(err, val.Type()) + } + i := val.Interface().(*big.Int) + if i == nil { + i = new(big.Int) + val.Set(reflect.ValueOf(i)) + } + // Reject leading zero bytes + if len(b) > 0 && b[0] == 0 { + return wrapStreamError(ErrCanonInt, val.Type()) + } + i.SetBytes(b) + return nil +} + +func makeListDecoder(typ reflect.Type, tag tags) (decoder, error) { + etype := typ.Elem() + if etype.Kind() == reflect.Uint8 && !reflect.PtrTo(etype).Implements(decoderInterface) { + if typ.Kind() == reflect.Array { + return decodeByteArray, nil + } + return decodeByteSlice, nil + } + etypeinfo := cachedTypeInfo1(etype, tags{}) + if etypeinfo.decoderErr != nil { + return nil, etypeinfo.decoderErr + } + var dec decoder + switch { + case typ.Kind() == reflect.Array: + dec = func(s *Stream, val reflect.Value) error { + return decodeListArray(s, val, etypeinfo.decoder) + } + case tag.tail: + // A slice with "tail" tag can occur as the last field + // of a struct and is supposed to swallow all remaining + // list elements. The struct decoder already called s.List, + // proceed directly to decoding the elements. + dec = func(s *Stream, val reflect.Value) error { + return decodeSliceElems(s, val, etypeinfo.decoder) + } + default: + dec = func(s *Stream, val reflect.Value) error { + return decodeListSlice(s, val, etypeinfo.decoder) + } + } + return dec, nil +} + +func decodeListSlice(s *Stream, val reflect.Value, elemdec decoder) error { + size, err := s.List() + if err != nil { + return wrapStreamError(err, val.Type()) + } + if size == 0 { + val.Set(reflect.MakeSlice(val.Type(), 0, 0)) + return s.ListEnd() + } + if err := decodeSliceElems(s, val, elemdec); err != nil { + return err + } + return s.ListEnd() +} + +func decodeSliceElems(s *Stream, val reflect.Value, elemdec decoder) error { + i := 0 + for ; ; i++ { + // grow slice if necessary + if i >= val.Cap() { + newcap := val.Cap() + val.Cap()/2 + if newcap < 4 { + newcap = 4 + } + newv := reflect.MakeSlice(val.Type(), val.Len(), newcap) + reflect.Copy(newv, val) + val.Set(newv) + } + if i >= val.Len() { + val.SetLen(i + 1) + } + // decode into element + if err := elemdec(s, val.Index(i)); err == EOL { + break + } else if err != nil { + return addErrorContext(err, fmt.Sprint("[", i, "]")) + } + } + if i < val.Len() { + val.SetLen(i) + } + return nil +} + +func decodeListArray(s *Stream, val reflect.Value, elemdec decoder) error { + if _, err := s.List(); err != nil { + return wrapStreamError(err, val.Type()) + } + vlen := val.Len() + i := 0 + for ; i < vlen; i++ { + if err := elemdec(s, val.Index(i)); err == EOL { + break + } else if err != nil { + return addErrorContext(err, fmt.Sprint("[", i, "]")) + } + } + if i < vlen { + return &decodeError{msg: "input list has too few elements", typ: val.Type()} + } + return wrapStreamError(s.ListEnd(), val.Type()) +} + +func decodeByteSlice(s *Stream, val reflect.Value) error { + b, err := s.Bytes() + if err != nil { + return wrapStreamError(err, val.Type()) + } + val.SetBytes(b) + return nil +} + +func decodeByteArray(s *Stream, val reflect.Value) error { + kind, size, err := s.Kind() + if err != nil { + return err + } + vlen := val.Len() + switch kind { + case Byte: + if vlen == 0 { + return &decodeError{msg: "input string too long", typ: val.Type()} + } + if vlen > 1 { + return &decodeError{msg: "input string too short", typ: val.Type()} + } + bv, _ := s.Uint() + val.Index(0).SetUint(bv) + case String: + if uint64(vlen) < size { + return &decodeError{msg: "input string too long", typ: val.Type()} + } + if uint64(vlen) > size { + return &decodeError{msg: "input string too short", typ: val.Type()} + } + slice := val.Slice(0, vlen).Interface().([]byte) + if err := s.readFull(slice); err != nil { + return err + } + // Reject cases where single byte encoding should have been used. + if size == 1 && slice[0] < 128 { + return wrapStreamError(ErrCanonSize, val.Type()) + } + case List: + return wrapStreamError(ErrExpectedString, val.Type()) + } + return nil +} + +func makeStructDecoder(typ reflect.Type) (decoder, error) { + fields, err := structFields(typ) + if err != nil { + return nil, err + } + for _, f := range fields { + if f.info.decoderErr != nil { + return nil, structFieldError{typ, f.index, f.info.decoderErr} + } + } + dec := func(s *Stream, val reflect.Value) (err error) { + if _, err := s.List(); err != nil { + return wrapStreamError(err, typ) + } + for _, f := range fields { + err := f.info.decoder(s, val.Field(f.index)) + if err == EOL { + return &decodeError{msg: "too few elements", typ: typ} + } else if err != nil { + return addErrorContext(err, "."+typ.Field(f.index).Name) + } + } + return wrapStreamError(s.ListEnd(), typ) + } + return dec, nil +} + +// makePtrDecoder creates a decoder that decodes into the pointer's element type. +func makePtrDecoder(typ reflect.Type, tag tags) (decoder, error) { + etype := typ.Elem() + etypeinfo := cachedTypeInfo1(etype, tags{}) + switch { + case etypeinfo.decoderErr != nil: + return nil, etypeinfo.decoderErr + case !tag.nilOK: + return makeSimplePtrDecoder(etype, etypeinfo), nil + default: + return makeNilPtrDecoder(etype, etypeinfo, tag.nilKind), nil + } +} + +func makeSimplePtrDecoder(etype reflect.Type, etypeinfo *typeinfo) decoder { + return func(s *Stream, val reflect.Value) (err error) { + newval := val + if val.IsNil() { + newval = reflect.New(etype) + } + if err = etypeinfo.decoder(s, newval.Elem()); err == nil { + val.Set(newval) + } + return err + } +} + +// makeNilPtrDecoder creates a decoder that decodes empty values as nil. Non-empty +// values are decoded into a value of the element type, just like makePtrDecoder does. +// +// This decoder is used for pointer-typed struct fields with struct tag "nil". +func makeNilPtrDecoder(etype reflect.Type, etypeinfo *typeinfo, nilKind Kind) decoder { + typ := reflect.PtrTo(etype) + nilPtr := reflect.Zero(typ) + return func(s *Stream, val reflect.Value) (err error) { + kind, size, err := s.Kind() + if err != nil { + val.Set(nilPtr) + return wrapStreamError(err, typ) + } + // Handle empty values as a nil pointer. + if kind != Byte && size == 0 { + if kind != nilKind { + return &decodeError{ + msg: fmt.Sprintf("wrong kind of empty value (got %v, want %v)", kind, nilKind), + typ: typ, + } + } + // rearm s.Kind. This is important because the input + // position must advance to the next value even though + // we don't read anything. + s.kind = -1 + val.Set(nilPtr) + return nil + } + newval := val + if val.IsNil() { + newval = reflect.New(etype) + } + if err = etypeinfo.decoder(s, newval.Elem()); err == nil { + val.Set(newval) + } + return err + } +} + +var ifsliceType = reflect.TypeOf([]interface{}{}) + +func decodeInterface(s *Stream, val reflect.Value) error { + if val.Type().NumMethod() != 0 { + return fmt.Errorf("rlp: type %v is not RLP-serializable", val.Type()) + } + kind, _, err := s.Kind() + if err != nil { + return err + } + if kind == List { + slice := reflect.New(ifsliceType).Elem() + if err := decodeListSlice(s, slice, decodeInterface); err != nil { + return err + } + val.Set(slice) + } else { + b, err := s.Bytes() + if err != nil { + return err + } + val.Set(reflect.ValueOf(b)) + } + return nil +} + +func decodeDecoder(s *Stream, val reflect.Value) error { + return val.Addr().Interface().(Decoder).DecodeRLP(s) +} + +// Kind represents the kind of value contained in an RLP stream. +type Kind int + +const ( + Byte Kind = iota + String + List +) + +func (k Kind) String() string { + switch k { + case Byte: + return "Byte" + case String: + return "String" + case List: + return "List" + default: + return fmt.Sprintf("Unknown(%d)", k) + } +} + +// ByteReader must be implemented by any input reader for a Stream. It +// is implemented by e.g. bufio.Reader and bytes.Reader. +type ByteReader interface { + io.Reader + io.ByteReader +} + +// Stream can be used for piecemeal decoding of an input stream. This +// is useful if the input is very large or if the decoding rules for a +// type depend on the input structure. Stream does not keep an +// internal buffer. After decoding a value, the input reader will be +// positioned just before the type information for the next value. +// +// When decoding a list and the input position reaches the declared +// length of the list, all operations will return error EOL. +// The end of the list must be acknowledged using ListEnd to continue +// reading the enclosing list. +// +// Stream is not safe for concurrent use. +type Stream struct { + r ByteReader + + // number of bytes remaining to be read from r. + remaining uint64 + limited bool + + // auxiliary buffer for integer decoding + uintbuf []byte + + kind Kind // kind of value ahead + size uint64 // size of value ahead + byteval byte // value of single byte in type tag + kinderr error // error from last readKind + stack []listpos +} + +type listpos struct{ pos, size uint64 } + +// NewStream creates a new decoding stream reading from r. +// +// If r implements the ByteReader interface, Stream will +// not introduce any buffering. +// +// For non-toplevel values, Stream returns ErrElemTooLarge +// for values that do not fit into the enclosing list. +// +// Stream supports an optional input limit. If a limit is set, the +// size of any toplevel value will be checked against the remaining +// input length. Stream operations that encounter a value exceeding +// the remaining input length will return ErrValueTooLarge. The limit +// can be set by passing a non-zero value for inputLimit. +// +// If r is a bytes.Reader or strings.Reader, the input limit is set to +// the length of r's underlying data unless an explicit limit is +// provided. +func NewStream(r io.Reader, inputLimit uint64) *Stream { + s := new(Stream) + s.Reset(r, inputLimit) + return s +} + +// NewListStream creates a new stream that pretends to be positioned +// at an encoded list of the given length. +func NewListStream(r io.Reader, len uint64) *Stream { + s := new(Stream) + s.Reset(r, len) + s.kind = List + s.size = len + return s +} + +// Bytes reads an RLP string and returns its contents as a byte slice. +// If the input does not contain an RLP string, the returned +// error will be ErrExpectedString. +func (s *Stream) Bytes() ([]byte, error) { + kind, size, err := s.Kind() + if err != nil { + return nil, err + } + switch kind { + case Byte: + s.kind = -1 // rearm Kind + return []byte{s.byteval}, nil + case String: + b := make([]byte, size) + if err = s.readFull(b); err != nil { + return nil, err + } + if size == 1 && b[0] < 128 { + return nil, ErrCanonSize + } + return b, nil + default: + return nil, ErrExpectedString + } +} + +// Raw reads a raw encoded value including RLP type information. +func (s *Stream) Raw() ([]byte, error) { + kind, size, err := s.Kind() + if err != nil { + return nil, err + } + if kind == Byte { + s.kind = -1 // rearm Kind + return []byte{s.byteval}, nil + } + // the original header has already been read and is no longer + // available. read content and put a new header in front of it. + start := headsize(size) + buf := make([]byte, uint64(start)+size) + if err := s.readFull(buf[start:]); err != nil { + return nil, err + } + if kind == String { + puthead(buf, 0x80, 0xB7, size) + } else { + puthead(buf, 0xC0, 0xF7, size) + } + return buf, nil +} + +// Uint reads an RLP string of up to 8 bytes and returns its contents +// as an unsigned integer. If the input does not contain an RLP string, the +// returned error will be ErrExpectedString. +func (s *Stream) Uint() (uint64, error) { + return s.uint(64) +} + +func (s *Stream) uint(maxbits int) (uint64, error) { + kind, size, err := s.Kind() + if err != nil { + return 0, err + } + switch kind { + case Byte: + if s.byteval == 0 { + return 0, ErrCanonInt + } + s.kind = -1 // rearm Kind + return uint64(s.byteval), nil + case String: + if size > uint64(maxbits/8) { + return 0, errUintOverflow + } + v, err := s.readUint(byte(size)) + switch { + case err == ErrCanonSize: + // Adjust error because we're not reading a size right now. + return 0, ErrCanonInt + case err != nil: + return 0, err + case size > 0 && v < 128: + return 0, ErrCanonSize + default: + return v, nil + } + default: + return 0, ErrExpectedString + } +} + +// Bool reads an RLP string of up to 1 byte and returns its contents +// as a boolean. If the input does not contain an RLP string, the +// returned error will be ErrExpectedString. +func (s *Stream) Bool() (bool, error) { + num, err := s.uint(8) + if err != nil { + return false, err + } + switch num { + case 0: + return false, nil + case 1: + return true, nil + default: + return false, fmt.Errorf("rlp: invalid boolean value: %d", num) + } +} + +// List starts decoding an RLP list. If the input does not contain a +// list, the returned error will be ErrExpectedList. When the list's +// end has been reached, any Stream operation will return EOL. +func (s *Stream) List() (size uint64, err error) { + kind, size, err := s.Kind() + if err != nil { + return 0, err + } + if kind != List { + return 0, ErrExpectedList + } + s.stack = append(s.stack, listpos{0, size}) + s.kind = -1 + s.size = 0 + return size, nil +} + +// ListEnd returns to the enclosing list. +// The input reader must be positioned at the end of a list. +func (s *Stream) ListEnd() error { + if len(s.stack) == 0 { + return errNotInList + } + tos := s.stack[len(s.stack)-1] + if tos.pos != tos.size { + return errNotAtEOL + } + s.stack = s.stack[:len(s.stack)-1] // pop + if len(s.stack) > 0 { + s.stack[len(s.stack)-1].pos += tos.size + } + s.kind = -1 + s.size = 0 + return nil +} + +// Decode decodes a value and stores the result in the value pointed +// to by val. Please see the documentation for the Decode function +// to learn about the decoding rules. +func (s *Stream) Decode(val interface{}) error { + if val == nil { + return errDecodeIntoNil + } + rval := reflect.ValueOf(val) + rtyp := rval.Type() + if rtyp.Kind() != reflect.Ptr { + return errNoPointer + } + if rval.IsNil() { + return errDecodeIntoNil + } + decoder, err := cachedDecoder(rtyp.Elem()) + if err != nil { + return err + } + + err = decoder(s, rval.Elem()) + if decErr, ok := err.(*decodeError); ok && len(decErr.ctx) > 0 { + // add decode target type to error so context has more meaning + decErr.ctx = append(decErr.ctx, fmt.Sprint("(", rtyp.Elem(), ")")) + } + return err +} + +// Reset discards any information about the current decoding context +// and starts reading from r. This method is meant to facilitate reuse +// of a preallocated Stream across many decoding operations. +// +// If r does not also implement ByteReader, Stream will do its own +// buffering. +func (s *Stream) Reset(r io.Reader, inputLimit uint64) { + if inputLimit > 0 { + s.remaining = inputLimit + s.limited = true + } else { + // Attempt to automatically discover + // the limit when reading from a byte slice. + switch br := r.(type) { + case *bytes.Reader: + s.remaining = uint64(br.Len()) + s.limited = true + case *strings.Reader: + s.remaining = uint64(br.Len()) + s.limited = true + default: + s.limited = false + } + } + // Wrap r with a buffer if it doesn't have one. + bufr, ok := r.(ByteReader) + if !ok { + bufr = bufio.NewReader(r) + } + s.r = bufr + // Reset the decoding context. + s.stack = s.stack[:0] + s.size = 0 + s.kind = -1 + s.kinderr = nil + if s.uintbuf == nil { + s.uintbuf = make([]byte, 8) + } + s.byteval = 0 +} + +// Kind returns the kind and size of the next value in the +// input stream. +// +// The returned size is the number of bytes that make up the value. +// For kind == Byte, the size is zero because the value is +// contained in the type tag. +// +// The first call to Kind will read size information from the input +// reader and leave it positioned at the start of the actual bytes of +// the value. Subsequent calls to Kind (until the value is decoded) +// will not advance the input reader and return cached information. +func (s *Stream) Kind() (kind Kind, size uint64, err error) { + var tos *listpos + if len(s.stack) > 0 { + tos = &s.stack[len(s.stack)-1] + } + if s.kind < 0 { + s.kinderr = nil + // Don't read further if we're at the end of the + // innermost list. + if tos != nil && tos.pos == tos.size { + return 0, 0, EOL + } + s.kind, s.size, s.kinderr = s.readKind() + if s.kinderr == nil { + if tos == nil { + // At toplevel, check that the value is smaller + // than the remaining input length. + if s.limited && s.size > s.remaining { + s.kinderr = ErrValueTooLarge + } + } else { + // Inside a list, check that the value doesn't overflow the list. + if s.size > tos.size-tos.pos { + s.kinderr = ErrElemTooLarge + } + } + } + } + // Note: this might return a sticky error generated + // by an earlier call to readKind. + return s.kind, s.size, s.kinderr +} + +func (s *Stream) readKind() (kind Kind, size uint64, err error) { + b, err := s.readByte() + if err != nil { + if len(s.stack) == 0 { + // At toplevel, Adjust the error to actual EOF. io.EOF is + // used by callers to determine when to stop decoding. + switch err { + case io.ErrUnexpectedEOF: + err = io.EOF + case ErrValueTooLarge: + err = io.EOF + } + } + return 0, 0, err + } + s.byteval = 0 + switch { + case b < 0x80: + // For a single byte whose value is in the [0x00, 0x7F] range, that byte + // is its own RLP encoding. + s.byteval = b + return Byte, 0, nil + case b < 0xB8: + // Otherwise, if a string is 0-55 bytes long, + // the RLP encoding consists of a single byte with value 0x80 plus the + // length of the string followed by the string. The range of the first + // byte is thus [0x80, 0xB7]. + return String, uint64(b - 0x80), nil + case b < 0xC0: + // If a string is more than 55 bytes long, the + // RLP encoding consists of a single byte with value 0xB7 plus the length + // of the length of the string in binary form, followed by the length of + // the string, followed by the string. For example, a length-1024 string + // would be encoded as 0xB90400 followed by the string. The range of + // the first byte is thus [0xB8, 0xBF]. + size, err = s.readUint(b - 0xB7) + if err == nil && size < 56 { + err = ErrCanonSize + } + return String, size, err + case b < 0xF8: + // If the total payload of a list + // (i.e. the combined length of all its items) is 0-55 bytes long, the + // RLP encoding consists of a single byte with value 0xC0 plus the length + // of the list followed by the concatenation of the RLP encodings of the + // items. The range of the first byte is thus [0xC0, 0xF7]. + return List, uint64(b - 0xC0), nil + default: + // If the total payload of a list is more than 55 bytes long, + // the RLP encoding consists of a single byte with value 0xF7 + // plus the length of the length of the payload in binary + // form, followed by the length of the payload, followed by + // the concatenation of the RLP encodings of the items. The + // range of the first byte is thus [0xF8, 0xFF]. + size, err = s.readUint(b - 0xF7) + if err == nil && size < 56 { + err = ErrCanonSize + } + return List, size, err + } +} + +func (s *Stream) readUint(size byte) (uint64, error) { + switch size { + case 0: + s.kind = -1 // rearm Kind + return 0, nil + case 1: + b, err := s.readByte() + return uint64(b), err + default: + start := int(8 - size) + for i := 0; i < start; i++ { + s.uintbuf[i] = 0 + } + if err := s.readFull(s.uintbuf[start:]); err != nil { + return 0, err + } + if s.uintbuf[start] == 0 { + // Note: readUint is also used to decode integer + // values. The error needs to be adjusted to become + // ErrCanonInt in this case. + return 0, ErrCanonSize + } + return binary.BigEndian.Uint64(s.uintbuf), nil + } +} + +func (s *Stream) readFull(buf []byte) (err error) { + if err := s.willRead(uint64(len(buf))); err != nil { + return err + } + var nn, n int + for n < len(buf) && err == nil { + nn, err = s.r.Read(buf[n:]) + n += nn + } + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return err +} + +func (s *Stream) readByte() (byte, error) { + if err := s.willRead(1); err != nil { + return 0, err + } + b, err := s.r.ReadByte() + if err == io.EOF { + err = io.ErrUnexpectedEOF + } + return b, err +} + +func (s *Stream) willRead(n uint64) error { + s.kind = -1 // rearm Kind + + if len(s.stack) > 0 { + // check list overflow + tos := s.stack[len(s.stack)-1] + if n > tos.size-tos.pos { + return ErrElemTooLarge + } + s.stack[len(s.stack)-1].pos += n + } + if s.limited { + if n > s.remaining { + return ErrValueTooLarge + } + s.remaining -= n + } + return nil +} diff --git a/bsc/rlp/decode_tail_test.go b/bsc/rlp/decode_tail_test.go new file mode 100644 index 0000000000..884c1148b2 --- /dev/null +++ b/bsc/rlp/decode_tail_test.go @@ -0,0 +1,49 @@ +// Copyright 2015 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "bytes" + "fmt" +) + +type structWithTail struct { + A, B uint + C []uint `rlp:"tail"` +} + +func ExampleDecode_structTagTail() { + // In this example, the "tail" struct tag is used to decode lists of + // differing length into a struct. + var val structWithTail + + err := Decode(bytes.NewReader([]byte{0xC4, 0x01, 0x02, 0x03, 0x04}), &val) + fmt.Printf("with 4 elements: err=%v val=%v\n", err, val) + + err = Decode(bytes.NewReader([]byte{0xC6, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06}), &val) + fmt.Printf("with 6 elements: err=%v val=%v\n", err, val) + + // Note that at least two list elements must be present to + // fill fields A and B: + err = Decode(bytes.NewReader([]byte{0xC1, 0x01}), &val) + fmt.Printf("with 1 element: err=%q\n", err) + + // Output: + // with 4 elements: err= val={1 2 [3 4]} + // with 6 elements: err= val={1 2 [3 4 5 6]} + // with 1 element: err="rlp: too few elements for rlp.structWithTail" +} diff --git a/bsc/rlp/decode_test.go b/bsc/rlp/decode_test.go new file mode 100644 index 0000000000..167e9974b9 --- /dev/null +++ b/bsc/rlp/decode_test.go @@ -0,0 +1,929 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "bytes" + "encoding/hex" + "errors" + "fmt" + "io" + "math/big" + "reflect" + "strings" + "testing" +) + +func TestStreamKind(t *testing.T) { + tests := []struct { + input string + wantKind Kind + wantLen uint64 + }{ + {"00", Byte, 0}, + {"01", Byte, 0}, + {"7F", Byte, 0}, + {"80", String, 0}, + {"B7", String, 55}, + {"B90400", String, 1024}, + {"BFFFFFFFFFFFFFFFFF", String, ^uint64(0)}, + {"C0", List, 0}, + {"C8", List, 8}, + {"F7", List, 55}, + {"F90400", List, 1024}, + {"FFFFFFFFFFFFFFFFFF", List, ^uint64(0)}, + } + + for i, test := range tests { + // using plainReader to inhibit input limit errors. + s := NewStream(newPlainReader(unhex(test.input)), 0) + kind, len, err := s.Kind() + if err != nil { + t.Errorf("test %d: Kind returned error: %v", i, err) + continue + } + if kind != test.wantKind { + t.Errorf("test %d: kind mismatch: got %d, want %d", i, kind, test.wantKind) + } + if len != test.wantLen { + t.Errorf("test %d: len mismatch: got %d, want %d", i, len, test.wantLen) + } + } +} + +func TestNewListStream(t *testing.T) { + ls := NewListStream(bytes.NewReader(unhex("0101010101")), 3) + if k, size, err := ls.Kind(); k != List || size != 3 || err != nil { + t.Errorf("Kind() returned (%v, %d, %v), expected (List, 3, nil)", k, size, err) + } + if size, err := ls.List(); size != 3 || err != nil { + t.Errorf("List() returned (%d, %v), expected (3, nil)", size, err) + } + for i := 0; i < 3; i++ { + if val, err := ls.Uint(); val != 1 || err != nil { + t.Errorf("Uint() returned (%d, %v), expected (1, nil)", val, err) + } + } + if err := ls.ListEnd(); err != nil { + t.Errorf("ListEnd() returned %v, expected (3, nil)", err) + } +} + +func TestStreamErrors(t *testing.T) { + withoutInputLimit := func(b []byte) *Stream { + return NewStream(newPlainReader(b), 0) + } + withCustomInputLimit := func(limit uint64) func([]byte) *Stream { + return func(b []byte) *Stream { + return NewStream(bytes.NewReader(b), limit) + } + } + + type calls []string + tests := []struct { + string + calls + newStream func([]byte) *Stream // uses bytes.Reader if nil + error error + }{ + {"C0", calls{"Bytes"}, nil, ErrExpectedString}, + {"C0", calls{"Uint"}, nil, ErrExpectedString}, + {"89000000000000000001", calls{"Uint"}, nil, errUintOverflow}, + {"00", calls{"List"}, nil, ErrExpectedList}, + {"80", calls{"List"}, nil, ErrExpectedList}, + {"C0", calls{"List", "Uint"}, nil, EOL}, + {"C8C9010101010101010101", calls{"List", "Kind"}, nil, ErrElemTooLarge}, + {"C3C2010201", calls{"List", "List", "Uint", "Uint", "ListEnd", "Uint"}, nil, EOL}, + {"00", calls{"ListEnd"}, nil, errNotInList}, + {"C401020304", calls{"List", "Uint", "ListEnd"}, nil, errNotAtEOL}, + + // Non-canonical integers (e.g. leading zero bytes). + {"00", calls{"Uint"}, nil, ErrCanonInt}, + {"820002", calls{"Uint"}, nil, ErrCanonInt}, + {"8133", calls{"Uint"}, nil, ErrCanonSize}, + {"817F", calls{"Uint"}, nil, ErrCanonSize}, + {"8180", calls{"Uint"}, nil, nil}, + + // Non-valid boolean + {"02", calls{"Bool"}, nil, errors.New("rlp: invalid boolean value: 2")}, + + // Size tags must use the smallest possible encoding. + // Leading zero bytes in the size tag are also rejected. + {"8100", calls{"Uint"}, nil, ErrCanonSize}, + {"8100", calls{"Bytes"}, nil, ErrCanonSize}, + {"8101", calls{"Bytes"}, nil, ErrCanonSize}, + {"817F", calls{"Bytes"}, nil, ErrCanonSize}, + {"8180", calls{"Bytes"}, nil, nil}, + {"B800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"B90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"B90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"BA0002FFFF", calls{"Bytes"}, withoutInputLimit, ErrCanonSize}, + {"F800", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"F90000", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"F90055", calls{"Kind"}, withoutInputLimit, ErrCanonSize}, + {"FA0002FFFF", calls{"List"}, withoutInputLimit, ErrCanonSize}, + + // Expected EOF + {"", calls{"Kind"}, nil, io.EOF}, + {"", calls{"Uint"}, nil, io.EOF}, + {"", calls{"List"}, nil, io.EOF}, + {"8180", calls{"Uint", "Uint"}, nil, io.EOF}, + {"C0", calls{"List", "ListEnd", "List"}, nil, io.EOF}, + + {"", calls{"List"}, withoutInputLimit, io.EOF}, + {"8180", calls{"Uint", "Uint"}, withoutInputLimit, io.EOF}, + {"C0", calls{"List", "ListEnd", "List"}, withoutInputLimit, io.EOF}, + + // Input limit errors. + {"81", calls{"Bytes"}, nil, ErrValueTooLarge}, + {"81", calls{"Uint"}, nil, ErrValueTooLarge}, + {"81", calls{"Raw"}, nil, ErrValueTooLarge}, + {"BFFFFFFFFFFFFFFFFFFF", calls{"Bytes"}, nil, ErrValueTooLarge}, + {"C801", calls{"List"}, nil, ErrValueTooLarge}, + + // Test for list element size check overflow. + {"CD04040404FFFFFFFFFFFFFFFFFF0303", calls{"List", "Uint", "Uint", "Uint", "Uint", "List"}, nil, ErrElemTooLarge}, + + // Test for input limit overflow. Since we are counting the limit + // down toward zero in Stream.remaining, reading too far can overflow + // remaining to a large value, effectively disabling the limit. + {"C40102030401", calls{"Raw", "Uint"}, withCustomInputLimit(5), io.EOF}, + {"C4010203048180", calls{"Raw", "Uint"}, withCustomInputLimit(6), ErrValueTooLarge}, + + // Check that the same calls are fine without a limit. + {"C40102030401", calls{"Raw", "Uint"}, withoutInputLimit, nil}, + {"C4010203048180", calls{"Raw", "Uint"}, withoutInputLimit, nil}, + + // Unexpected EOF. This only happens when there is + // no input limit, so the reader needs to be 'dumbed down'. + {"81", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, + {"81", calls{"Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, + {"BFFFFFFFFFFFFFFF", calls{"Bytes"}, withoutInputLimit, io.ErrUnexpectedEOF}, + {"C801", calls{"List", "Uint", "Uint"}, withoutInputLimit, io.ErrUnexpectedEOF}, + + // This test verifies that the input position is advanced + // correctly when calling Bytes for empty strings. Kind can be called + // any number of times in between and doesn't advance. + {"C3808080", calls{ + "List", // enter the list + "Bytes", // past first element + + "Kind", "Kind", "Kind", // this shouldn't advance + + "Bytes", // past second element + + "Kind", "Kind", // can't hurt to try + + "Bytes", // past final element + "Bytes", // this one should fail + }, nil, EOL}, + } + +testfor: + for i, test := range tests { + if test.newStream == nil { + test.newStream = func(b []byte) *Stream { return NewStream(bytes.NewReader(b), 0) } + } + s := test.newStream(unhex(test.string)) + rs := reflect.ValueOf(s) + for j, call := range test.calls { + fval := rs.MethodByName(call) + ret := fval.Call(nil) + err := "" + if lastret := ret[len(ret)-1].Interface(); lastret != nil { + err = lastret.(error).Error() + } + if j == len(test.calls)-1 { + want := "" + if test.error != nil { + want = test.error.Error() + } + if err != want { + t.Log(test) + t.Errorf("test %d: last call (%s) error mismatch\ngot: %s\nwant: %s", + i, call, err, test.error) + } + } else if err != "" { + t.Log(test) + t.Errorf("test %d: call %d (%s) unexpected error: %q", i, j, call, err) + continue testfor + } + } + } +} + +func TestStreamList(t *testing.T) { + s := NewStream(bytes.NewReader(unhex("C80102030405060708")), 0) + + len, err := s.List() + if err != nil { + t.Fatalf("List error: %v", err) + } + if len != 8 { + t.Fatalf("List returned invalid length, got %d, want 8", len) + } + + for i := uint64(1); i <= 8; i++ { + v, err := s.Uint() + if err != nil { + t.Fatalf("Uint error: %v", err) + } + if i != v { + t.Errorf("Uint returned wrong value, got %d, want %d", v, i) + } + } + + if _, err := s.Uint(); err != EOL { + t.Errorf("Uint error mismatch, got %v, want %v", err, EOL) + } + if err = s.ListEnd(); err != nil { + t.Fatalf("ListEnd error: %v", err) + } +} + +func TestStreamRaw(t *testing.T) { + tests := []struct { + input string + output string + }{ + { + "C58401010101", + "8401010101", + }, + { + "F842B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + "B84001010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101010101", + }, + } + for i, tt := range tests { + s := NewStream(bytes.NewReader(unhex(tt.input)), 0) + s.List() + + want := unhex(tt.output) + raw, err := s.Raw() + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(want, raw) { + t.Errorf("test %d: raw mismatch: got %x, want %x", i, raw, want) + } + } +} + +func TestDecodeErrors(t *testing.T) { + r := bytes.NewReader(nil) + + if err := Decode(r, nil); err != errDecodeIntoNil { + t.Errorf("Decode(r, nil) error mismatch, got %q, want %q", err, errDecodeIntoNil) + } + + var nilptr *struct{} + if err := Decode(r, nilptr); err != errDecodeIntoNil { + t.Errorf("Decode(r, nilptr) error mismatch, got %q, want %q", err, errDecodeIntoNil) + } + + if err := Decode(r, struct{}{}); err != errNoPointer { + t.Errorf("Decode(r, struct{}{}) error mismatch, got %q, want %q", err, errNoPointer) + } + + expectErr := "rlp: type chan bool is not RLP-serializable" + if err := Decode(r, new(chan bool)); err == nil || err.Error() != expectErr { + t.Errorf("Decode(r, new(chan bool)) error mismatch, got %q, want %q", err, expectErr) + } + + if err := Decode(r, new(uint)); err != io.EOF { + t.Errorf("Decode(r, new(int)) error mismatch, got %q, want %q", err, io.EOF) + } +} + +type decodeTest struct { + input string + ptr interface{} + value interface{} + error string +} + +type simplestruct struct { + A uint + B string +} + +type recstruct struct { + I uint + Child *recstruct `rlp:"nil"` +} + +type invalidNilTag struct { + X []byte `rlp:"nil"` +} + +type invalidTail1 struct { + A uint `rlp:"tail"` + B string +} + +type invalidTail2 struct { + A uint + B string `rlp:"tail"` +} + +type tailRaw struct { + A uint + Tail []RawValue `rlp:"tail"` +} + +type tailUint struct { + A uint + Tail []uint `rlp:"tail"` +} + +type tailPrivateFields struct { + A uint + Tail []uint `rlp:"tail"` + x, y bool //lint:ignore U1000 unused fields required for testing purposes. +} + +type nilListUint struct { + X *uint `rlp:"nilList"` +} + +type nilStringSlice struct { + X *[]uint `rlp:"nilString"` +} + +type intField struct { + X int +} + +var ( + veryBigInt = big.NewInt(0).Add( + big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), + big.NewInt(0xFFFF), + ) +) + +type hasIgnoredField struct { + A uint + B uint `rlp:"-"` + C uint +} + +var decodeTests = []decodeTest{ + // booleans + {input: "01", ptr: new(bool), value: true}, + {input: "80", ptr: new(bool), value: false}, + {input: "02", ptr: new(bool), error: "rlp: invalid boolean value: 2"}, + + // integers + {input: "05", ptr: new(uint32), value: uint32(5)}, + {input: "80", ptr: new(uint32), value: uint32(0)}, + {input: "820505", ptr: new(uint32), value: uint32(0x0505)}, + {input: "83050505", ptr: new(uint32), value: uint32(0x050505)}, + {input: "8405050505", ptr: new(uint32), value: uint32(0x05050505)}, + {input: "850505050505", ptr: new(uint32), error: "rlp: input string too long for uint32"}, + {input: "C0", ptr: new(uint32), error: "rlp: expected input string or byte for uint32"}, + {input: "00", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, + {input: "8105", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, + {input: "820004", ptr: new(uint32), error: "rlp: non-canonical integer (leading zero bytes) for uint32"}, + {input: "B8020004", ptr: new(uint32), error: "rlp: non-canonical size information for uint32"}, + + // slices + {input: "C0", ptr: new([]uint), value: []uint{}}, + {input: "C80102030405060708", ptr: new([]uint), value: []uint{1, 2, 3, 4, 5, 6, 7, 8}}, + {input: "F8020004", ptr: new([]uint), error: "rlp: non-canonical size information for []uint"}, + + // arrays + {input: "C50102030405", ptr: new([5]uint), value: [5]uint{1, 2, 3, 4, 5}}, + {input: "C0", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, + {input: "C102", ptr: new([5]uint), error: "rlp: input list has too few elements for [5]uint"}, + {input: "C6010203040506", ptr: new([5]uint), error: "rlp: input list has too many elements for [5]uint"}, + {input: "F8020004", ptr: new([5]uint), error: "rlp: non-canonical size information for [5]uint"}, + + // zero sized arrays + {input: "C0", ptr: new([0]uint), value: [0]uint{}}, + {input: "C101", ptr: new([0]uint), error: "rlp: input list has too many elements for [0]uint"}, + + // byte slices + {input: "01", ptr: new([]byte), value: []byte{1}}, + {input: "80", ptr: new([]byte), value: []byte{}}, + {input: "8D6162636465666768696A6B6C6D", ptr: new([]byte), value: []byte("abcdefghijklm")}, + {input: "C0", ptr: new([]byte), error: "rlp: expected input string or byte for []uint8"}, + {input: "8105", ptr: new([]byte), error: "rlp: non-canonical size information for []uint8"}, + + // byte arrays + {input: "02", ptr: new([1]byte), value: [1]byte{2}}, + {input: "8180", ptr: new([1]byte), value: [1]byte{128}}, + {input: "850102030405", ptr: new([5]byte), value: [5]byte{1, 2, 3, 4, 5}}, + + // byte array errors + {input: "02", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, + {input: "80", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, + {input: "820000", ptr: new([5]byte), error: "rlp: input string too short for [5]uint8"}, + {input: "C0", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, + {input: "C3010203", ptr: new([5]byte), error: "rlp: expected input string or byte for [5]uint8"}, + {input: "86010203040506", ptr: new([5]byte), error: "rlp: input string too long for [5]uint8"}, + {input: "8105", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, + {input: "817F", ptr: new([1]byte), error: "rlp: non-canonical size information for [1]uint8"}, + + // zero sized byte arrays + {input: "80", ptr: new([0]byte), value: [0]byte{}}, + {input: "01", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, + {input: "8101", ptr: new([0]byte), error: "rlp: input string too long for [0]uint8"}, + + // strings + {input: "00", ptr: new(string), value: "\000"}, + {input: "8D6162636465666768696A6B6C6D", ptr: new(string), value: "abcdefghijklm"}, + {input: "C0", ptr: new(string), error: "rlp: expected input string or byte for string"}, + + // big ints + {input: "01", ptr: new(*big.Int), value: big.NewInt(1)}, + {input: "89FFFFFFFFFFFFFFFFFF", ptr: new(*big.Int), value: veryBigInt}, + {input: "10", ptr: new(big.Int), value: *big.NewInt(16)}, // non-pointer also works + {input: "C0", ptr: new(*big.Int), error: "rlp: expected input string or byte for *big.Int"}, + {input: "820001", ptr: new(big.Int), error: "rlp: non-canonical integer (leading zero bytes) for *big.Int"}, + {input: "8105", ptr: new(big.Int), error: "rlp: non-canonical size information for *big.Int"}, + + // structs + { + input: "C50583343434", + ptr: new(simplestruct), + value: simplestruct{5, "444"}, + }, + { + input: "C601C402C203C0", + ptr: new(recstruct), + value: recstruct{1, &recstruct{2, &recstruct{3, nil}}}, + }, + + // struct errors + { + input: "C0", + ptr: new(simplestruct), + error: "rlp: too few elements for rlp.simplestruct", + }, + { + input: "C105", + ptr: new(simplestruct), + error: "rlp: too few elements for rlp.simplestruct", + }, + { + input: "C7C50583343434C0", + ptr: new([]*simplestruct), + error: "rlp: too few elements for rlp.simplestruct, decoding into ([]*rlp.simplestruct)[1]", + }, + { + input: "83222222", + ptr: new(simplestruct), + error: "rlp: expected input list for rlp.simplestruct", + }, + { + input: "C3010101", + ptr: new(simplestruct), + error: "rlp: input list has too many elements for rlp.simplestruct", + }, + { + input: "C501C3C00000", + ptr: new(recstruct), + error: "rlp: expected input string or byte for uint, decoding into (rlp.recstruct).Child.I", + }, + { + input: "C103", + ptr: new(intField), + error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)", + }, + { + input: "C50102C20102", + ptr: new(tailUint), + error: "rlp: expected input string or byte for uint, decoding into (rlp.tailUint).Tail[1]", + }, + { + input: "C0", + ptr: new(invalidNilTag), + error: `rlp: invalid struct tag "nil" for rlp.invalidNilTag.X (field is not a pointer)`, + }, + + // struct tag "tail" + { + input: "C3010203", + ptr: new(tailRaw), + value: tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, + }, + { + input: "C20102", + ptr: new(tailRaw), + value: tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, + }, + { + input: "C101", + ptr: new(tailRaw), + value: tailRaw{A: 1, Tail: []RawValue{}}, + }, + { + input: "C3010203", + ptr: new(tailPrivateFields), + value: tailPrivateFields{A: 1, Tail: []uint{2, 3}}, + }, + { + input: "C0", + ptr: new(invalidTail1), + error: `rlp: invalid struct tag "tail" for rlp.invalidTail1.A (must be on last field)`, + }, + { + input: "C0", + ptr: new(invalidTail2), + error: `rlp: invalid struct tag "tail" for rlp.invalidTail2.B (field type is not slice)`, + }, + + // struct tag "-" + { + input: "C20102", + ptr: new(hasIgnoredField), + value: hasIgnoredField{A: 1, C: 2}, + }, + + // struct tag "nilList" + { + input: "C180", + ptr: new(nilListUint), + error: "rlp: wrong kind of empty value (got String, want List) for *uint, decoding into (rlp.nilListUint).X", + }, + { + input: "C1C0", + ptr: new(nilListUint), + value: nilListUint{}, + }, + { + input: "C103", + ptr: new(nilListUint), + value: func() interface{} { + v := uint(3) + return nilListUint{X: &v} + }(), + }, + + // struct tag "nilString" + { + input: "C1C0", + ptr: new(nilStringSlice), + error: "rlp: wrong kind of empty value (got List, want String) for *[]uint, decoding into (rlp.nilStringSlice).X", + }, + { + input: "C180", + ptr: new(nilStringSlice), + value: nilStringSlice{}, + }, + { + input: "C2C103", + ptr: new(nilStringSlice), + value: nilStringSlice{X: &[]uint{3}}, + }, + + // RawValue + {input: "01", ptr: new(RawValue), value: RawValue(unhex("01"))}, + {input: "82FFFF", ptr: new(RawValue), value: RawValue(unhex("82FFFF"))}, + {input: "C20102", ptr: new([]RawValue), value: []RawValue{unhex("01"), unhex("02")}}, + + // pointers + {input: "00", ptr: new(*[]byte), value: &[]byte{0}}, + {input: "80", ptr: new(*uint), value: uintp(0)}, + {input: "C0", ptr: new(*uint), error: "rlp: expected input string or byte for uint"}, + {input: "07", ptr: new(*uint), value: uintp(7)}, + {input: "817F", ptr: new(*uint), error: "rlp: non-canonical size information for uint"}, + {input: "8180", ptr: new(*uint), value: uintp(0x80)}, + {input: "C109", ptr: new(*[]uint), value: &[]uint{9}}, + {input: "C58403030303", ptr: new(*[][]byte), value: &[][]byte{{3, 3, 3, 3}}}, + + // check that input position is advanced also for empty values. + {input: "C3808005", ptr: new([]*uint), value: []*uint{uintp(0), uintp(0), uintp(5)}}, + + // interface{} + {input: "00", ptr: new(interface{}), value: []byte{0}}, + {input: "01", ptr: new(interface{}), value: []byte{1}}, + {input: "80", ptr: new(interface{}), value: []byte{}}, + {input: "850505050505", ptr: new(interface{}), value: []byte{5, 5, 5, 5, 5}}, + {input: "C0", ptr: new(interface{}), value: []interface{}{}}, + {input: "C50183040404", ptr: new(interface{}), value: []interface{}{[]byte{1}, []byte{4, 4, 4}}}, + { + input: "C3010203", + ptr: new([]io.Reader), + error: "rlp: type io.Reader is not RLP-serializable", + }, + + // fuzzer crashes + { + input: "c330f9c030f93030ce3030303030303030bd303030303030", + ptr: new(interface{}), + error: "rlp: element is larger than containing list", + }, +} + +func uintp(i uint) *uint { return &i } + +func runTests(t *testing.T, decode func([]byte, interface{}) error) { + for i, test := range decodeTests { + input, err := hex.DecodeString(test.input) + if err != nil { + t.Errorf("test %d: invalid hex input %q", i, test.input) + continue + } + err = decode(input, test.ptr) + if err != nil && test.error == "" { + t.Errorf("test %d: unexpected Decode error: %v\ndecoding into %T\ninput %q", + i, err, test.ptr, test.input) + continue + } + if test.error != "" && fmt.Sprint(err) != test.error { + t.Errorf("test %d: Decode error mismatch\ngot %v\nwant %v\ndecoding into %T\ninput %q", + i, err, test.error, test.ptr, test.input) + continue + } + deref := reflect.ValueOf(test.ptr).Elem().Interface() + if err == nil && !reflect.DeepEqual(deref, test.value) { + t.Errorf("test %d: value mismatch\ngot %#v\nwant %#v\ndecoding into %T\ninput %q", + i, deref, test.value, test.ptr, test.input) + } + } +} + +func TestDecodeWithByteReader(t *testing.T) { + runTests(t, func(input []byte, into interface{}) error { + return Decode(bytes.NewReader(input), into) + }) +} + +// plainReader reads from a byte slice but does not +// implement ReadByte. It is also not recognized by the +// size validation. This is useful to test how the decoder +// behaves on a non-buffered input stream. +type plainReader []byte + +func newPlainReader(b []byte) io.Reader { + return (*plainReader)(&b) +} + +func (r *plainReader) Read(buf []byte) (n int, err error) { + if len(*r) == 0 { + return 0, io.EOF + } + n = copy(buf, *r) + *r = (*r)[n:] + return n, nil +} + +func TestDecodeWithNonByteReader(t *testing.T) { + runTests(t, func(input []byte, into interface{}) error { + return Decode(newPlainReader(input), into) + }) +} + +func TestDecodeStreamReset(t *testing.T) { + s := NewStream(nil, 0) + runTests(t, func(input []byte, into interface{}) error { + s.Reset(bytes.NewReader(input), 0) + return s.Decode(into) + }) +} + +type testDecoder struct{ called bool } + +func (t *testDecoder) DecodeRLP(s *Stream) error { + if _, err := s.Uint(); err != nil { + return err + } + t.called = true + return nil +} + +func TestDecodeDecoder(t *testing.T) { + var s struct { + T1 testDecoder + T2 *testDecoder + T3 **testDecoder + } + if err := Decode(bytes.NewReader(unhex("C3010203")), &s); err != nil { + t.Fatalf("Decode error: %v", err) + } + + if !s.T1.called { + t.Errorf("DecodeRLP was not called for (non-pointer) testDecoder") + } + + if s.T2 == nil { + t.Errorf("*testDecoder has not been allocated") + } else if !s.T2.called { + t.Errorf("DecodeRLP was not called for *testDecoder") + } + + if s.T3 == nil || *s.T3 == nil { + t.Errorf("**testDecoder has not been allocated") + } else if !(*s.T3).called { + t.Errorf("DecodeRLP was not called for **testDecoder") + } +} + +func TestDecodeDecoderNilPointer(t *testing.T) { + var s struct { + T1 *testDecoder `rlp:"nil"` + T2 *testDecoder + } + if err := Decode(bytes.NewReader(unhex("C2C002")), &s); err != nil { + t.Fatalf("Decode error: %v", err) + } + if s.T1 != nil { + t.Errorf("decoder T1 allocated for empty input (called: %v)", s.T1.called) + } + if s.T2 == nil || !s.T2.called { + t.Errorf("decoder T2 not allocated/called") + } +} + +type byteDecoder byte + +func (bd *byteDecoder) DecodeRLP(s *Stream) error { + _, err := s.Uint() + *bd = 255 + return err +} + +func (bd byteDecoder) called() bool { + return bd == 255 +} + +// This test verifies that the byte slice/byte array logic +// does not kick in for element types implementing Decoder. +func TestDecoderInByteSlice(t *testing.T) { + var slice []byteDecoder + if err := Decode(bytes.NewReader(unhex("C101")), &slice); err != nil { + t.Errorf("unexpected Decode error %v", err) + } else if !slice[0].called() { + t.Errorf("DecodeRLP not called for slice element") + } + + var array [1]byteDecoder + if err := Decode(bytes.NewReader(unhex("C101")), &array); err != nil { + t.Errorf("unexpected Decode error %v", err) + } else if !array[0].called() { + t.Errorf("DecodeRLP not called for array element") + } +} + +type unencodableDecoder func() + +func (f *unencodableDecoder) DecodeRLP(s *Stream) error { + if _, err := s.List(); err != nil { + return err + } + if err := s.ListEnd(); err != nil { + return err + } + *f = func() {} + return nil +} + +func TestDecoderFunc(t *testing.T) { + var x func() + if err := DecodeBytes([]byte{0xC0}, (*unencodableDecoder)(&x)); err != nil { + t.Fatal(err) + } + x() +} + +func ExampleDecode() { + input, _ := hex.DecodeString("C90A1486666F6F626172") + + type example struct { + A, B uint + String string + } + + var s example + err := Decode(bytes.NewReader(input), &s) + if err != nil { + fmt.Printf("Error: %v\n", err) + } else { + fmt.Printf("Decoded value: %#v\n", s) + } + // Output: + // Decoded value: rlp.example{A:0xa, B:0x14, String:"foobar"} +} + +func ExampleDecode_structTagNil() { + // In this example, we'll use the "nil" struct tag to change + // how a pointer-typed field is decoded. The input contains an RLP + // list of one element, an empty string. + input := []byte{0xC1, 0x80} + + // This type uses the normal rules. + // The empty input string is decoded as a pointer to an empty Go string. + var normalRules struct { + String *string + } + Decode(bytes.NewReader(input), &normalRules) + fmt.Printf("normal: String = %q\n", *normalRules.String) + + // This type uses the struct tag. + // The empty input string is decoded as a nil pointer. + var withEmptyOK struct { + String *string `rlp:"nil"` + } + Decode(bytes.NewReader(input), &withEmptyOK) + fmt.Printf("with nil tag: String = %v\n", withEmptyOK.String) + + // Output: + // normal: String = "" + // with nil tag: String = +} + +func ExampleStream() { + input, _ := hex.DecodeString("C90A1486666F6F626172") + s := NewStream(bytes.NewReader(input), 0) + + // Check what kind of value lies ahead + kind, size, _ := s.Kind() + fmt.Printf("Kind: %v size:%d\n", kind, size) + + // Enter the list + if _, err := s.List(); err != nil { + fmt.Printf("List error: %v\n", err) + return + } + + // Decode elements + fmt.Println(s.Uint()) + fmt.Println(s.Uint()) + fmt.Println(s.Bytes()) + + // Acknowledge end of list + if err := s.ListEnd(); err != nil { + fmt.Printf("ListEnd error: %v\n", err) + } + // Output: + // Kind: List size:9 + // 10 + // 20 + // [102 111 111 98 97 114] +} + +func BenchmarkDecode(b *testing.B) { + enc := encodeTestSlice(90000) + b.SetBytes(int64(len(enc))) + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + var s []uint + r := bytes.NewReader(enc) + if err := Decode(r, &s); err != nil { + b.Fatalf("Decode error: %v", err) + } + } +} + +func BenchmarkDecodeIntSliceReuse(b *testing.B) { + enc := encodeTestSlice(100000) + b.SetBytes(int64(len(enc))) + b.ReportAllocs() + b.ResetTimer() + + var s []uint + for i := 0; i < b.N; i++ { + r := bytes.NewReader(enc) + if err := Decode(r, &s); err != nil { + b.Fatalf("Decode error: %v", err) + } + } +} + +func encodeTestSlice(n uint) []byte { + s := make([]uint, n) + for i := uint(0); i < n; i++ { + s[i] = i + } + b, err := EncodeToBytes(s) + if err != nil { + panic(fmt.Sprintf("encode error: %v", err)) + } + return b +} + +func unhex(str string) []byte { + b, err := hex.DecodeString(strings.Replace(str, " ", "", -1)) + if err != nil { + panic(fmt.Sprintf("invalid hex string: %q", str)) + } + return b +} diff --git a/bsc/rlp/doc.go b/bsc/rlp/doc.go new file mode 100644 index 0000000000..7e6ee85200 --- /dev/null +++ b/bsc/rlp/doc.go @@ -0,0 +1,130 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +/* +Package rlp implements the RLP serialization format. + +The purpose of RLP (Recursive Linear Prefix) is to encode arbitrarily nested arrays of +binary data, and RLP is the main encoding method used to serialize objects in Ethereum. +The only purpose of RLP is to encode structure; encoding specific atomic data types (eg. +strings, ints, floats) is left up to higher-order protocols. In Ethereum integers must be +represented in big endian binary form with no leading zeroes (thus making the integer +value zero equivalent to the empty string). + +RLP values are distinguished by a type tag. The type tag precedes the value in the input +stream and defines the size and kind of the bytes that follow. + + +Encoding Rules + +Package rlp uses reflection and encodes RLP based on the Go type of the value. + +If the type implements the Encoder interface, Encode calls EncodeRLP. It does not +call EncodeRLP on nil pointer values. + +To encode a pointer, the value being pointed to is encoded. A nil pointer to a struct +type, slice or array always encodes as an empty RLP list unless the slice or array has +elememt type byte. A nil pointer to any other value encodes as the empty string. + +Struct values are encoded as an RLP list of all their encoded public fields. Recursive +struct types are supported. + +To encode slices and arrays, the elements are encoded as an RLP list of the value's +elements. Note that arrays and slices with element type uint8 or byte are always encoded +as an RLP string. + +A Go string is encoded as an RLP string. + +An unsigned integer value is encoded as an RLP string. Zero always encodes as an empty RLP +string. big.Int values are treated as integers. Signed integers (int, int8, int16, ...) +are not supported and will return an error when encoding. + +Boolean values are encoded as the unsigned integers zero (false) and one (true). + +An interface value encodes as the value contained in the interface. + +Floating point numbers, maps, channels and functions are not supported. + + +Decoding Rules + +Decoding uses the following type-dependent rules: + +If the type implements the Decoder interface, DecodeRLP is called. + +To decode into a pointer, the value will be decoded as the element type of the pointer. If +the pointer is nil, a new value of the pointer's element type is allocated. If the pointer +is non-nil, the existing value will be reused. Note that package rlp never leaves a +pointer-type struct field as nil unless one of the "nil" struct tags is present. + +To decode into a struct, decoding expects the input to be an RLP list. The decoded +elements of the list are assigned to each public field in the order given by the struct's +definition. The input list must contain an element for each decoded field. Decoding +returns an error if there are too few or too many elements for the struct. + +To decode into a slice, the input must be a list and the resulting slice will contain the +input elements in order. For byte slices, the input must be an RLP string. Array types +decode similarly, with the additional restriction that the number of input elements (or +bytes) must match the array's defined length. + +To decode into a Go string, the input must be an RLP string. The input bytes are taken +as-is and will not necessarily be valid UTF-8. + +To decode into an unsigned integer type, the input must also be an RLP string. The bytes +are interpreted as a big endian representation of the integer. If the RLP string is larger +than the bit size of the type, decoding will return an error. Decode also supports +*big.Int. There is no size limit for big integers. + +To decode into a boolean, the input must contain an unsigned integer of value zero (false) +or one (true). + +To decode into an interface value, one of these types is stored in the value: + + []interface{}, for RLP lists + []byte, for RLP strings + +Non-empty interface types are not supported when decoding. +Signed integers, floating point numbers, maps, channels and functions cannot be decoded into. + + +Struct Tags + +Package rlp honours certain struct tags: "-", "tail", "nil", "nilList" and "nilString". + +The "-" tag ignores fields. + +The "tail" tag, which may only be used on the last exported struct field, allows slurping +up any excess list elements into a slice. See examples for more details. + +The "nil" tag applies to pointer-typed fields and changes the decoding rules for the field +such that input values of size zero decode as a nil pointer. This tag can be useful when +decoding recursive types. + + type StructWithOptionalFoo struct { + Foo *[20]byte `rlp:"nil"` + } + +RLP supports two kinds of empty values: empty lists and empty strings. When using the +"nil" tag, the kind of empty value allowed for a type is chosen automatically. A struct +field whose Go type is a pointer to an unsigned integer, string, boolean or byte +array/slice expects an empty RLP string. Any other pointer field type encodes/decodes as +an empty RLP list. + +The choice of null value can be made explicit with the "nilList" and "nilString" struct +tags. Using these tags encodes/decodes a Go nil pointer value as the kind of empty +RLP value defined by the tag. +*/ +package rlp diff --git a/bsc/rlp/encode.go b/bsc/rlp/encode.go new file mode 100644 index 0000000000..9c9e8d706d --- /dev/null +++ b/bsc/rlp/encode.go @@ -0,0 +1,612 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "fmt" + "io" + "math/big" + "reflect" + "sync" +) + +var ( + // Common encoded values. + // These are useful when implementing EncodeRLP. + EmptyString = []byte{0x80} + EmptyList = []byte{0xC0} +) + +// Encoder is implemented by types that require custom +// encoding rules or want to encode private fields. +type Encoder interface { + // EncodeRLP should write the RLP encoding of its receiver to w. + // If the implementation is a pointer method, it may also be + // called for nil pointers. + // + // Implementations should generate valid RLP. The data written is + // not verified at the moment, but a future version might. It is + // recommended to write only a single value but writing multiple + // values or no value at all is also permitted. + EncodeRLP(io.Writer) error +} + +// Encode writes the RLP encoding of val to w. Note that Encode may +// perform many small writes in some cases. Consider making w +// buffered. +// +// Please see package-level documentation of encoding rules. +func Encode(w io.Writer, val interface{}) error { + if outer, ok := w.(*encbuf); ok { + // Encode was called by some type's EncodeRLP. + // Avoid copying by writing to the outer encbuf directly. + return outer.encode(val) + } + eb := encbufPool.Get().(*encbuf) + defer encbufPool.Put(eb) + eb.reset() + if err := eb.encode(val); err != nil { + return err + } + return eb.toWriter(w) +} + +// EncodeToBytes returns the RLP encoding of val. +// Please see package-level documentation for the encoding rules. +func EncodeToBytes(val interface{}) ([]byte, error) { + eb := encbufPool.Get().(*encbuf) + defer encbufPool.Put(eb) + eb.reset() + if err := eb.encode(val); err != nil { + return nil, err + } + return eb.toBytes(), nil +} + +// EncodeToReader returns a reader from which the RLP encoding of val +// can be read. The returned size is the total size of the encoded +// data. +// +// Please see the documentation of Encode for the encoding rules. +func EncodeToReader(val interface{}) (size int, r io.Reader, err error) { + eb := encbufPool.Get().(*encbuf) + eb.reset() + if err := eb.encode(val); err != nil { + return 0, nil, err + } + return eb.size(), &encReader{buf: eb}, nil +} + +type encbuf struct { + str []byte // string data, contains everything except list headers + lheads []*listhead // all list headers + lhsize int // sum of sizes of all encoded list headers + sizebuf []byte // 9-byte auxiliary buffer for uint encoding +} + +type listhead struct { + offset int // index of this header in string data + size int // total size of encoded data (including list headers) +} + +// encode writes head to the given buffer, which must be at least +// 9 bytes long. It returns the encoded bytes. +func (head *listhead) encode(buf []byte) []byte { + return buf[:puthead(buf, 0xC0, 0xF7, uint64(head.size))] +} + +// headsize returns the size of a list or string header +// for a value of the given size. +func headsize(size uint64) int { + if size < 56 { + return 1 + } + return 1 + intsize(size) +} + +// puthead writes a list or string header to buf. +// buf must be at least 9 bytes long. +func puthead(buf []byte, smalltag, largetag byte, size uint64) int { + if size < 56 { + buf[0] = smalltag + byte(size) + return 1 + } + sizesize := putint(buf[1:], size) + buf[0] = largetag + byte(sizesize) + return sizesize + 1 +} + +// encbufs are pooled. +var encbufPool = sync.Pool{ + New: func() interface{} { return &encbuf{sizebuf: make([]byte, 9)} }, +} + +func (w *encbuf) reset() { + w.lhsize = 0 + if w.str != nil { + w.str = w.str[:0] + } + if w.lheads != nil { + w.lheads = w.lheads[:0] + } +} + +// encbuf implements io.Writer so it can be passed it into EncodeRLP. +func (w *encbuf) Write(b []byte) (int, error) { + w.str = append(w.str, b...) + return len(b), nil +} + +func (w *encbuf) encode(val interface{}) error { + rval := reflect.ValueOf(val) + writer, err := cachedWriter(rval.Type()) + if err != nil { + return err + } + return writer(rval, w) +} + +func (w *encbuf) encodeStringHeader(size int) { + if size < 56 { + w.str = append(w.str, 0x80+byte(size)) + } else { + // TODO: encode to w.str directly + sizesize := putint(w.sizebuf[1:], uint64(size)) + w.sizebuf[0] = 0xB7 + byte(sizesize) + w.str = append(w.str, w.sizebuf[:sizesize+1]...) + } +} + +func (w *encbuf) encodeString(b []byte) { + if len(b) == 1 && b[0] <= 0x7F { + // fits single byte, no string header + w.str = append(w.str, b[0]) + } else { + w.encodeStringHeader(len(b)) + w.str = append(w.str, b...) + } +} + +func (w *encbuf) list() *listhead { + lh := &listhead{offset: len(w.str), size: w.lhsize} + w.lheads = append(w.lheads, lh) + return lh +} + +func (w *encbuf) listEnd(lh *listhead) { + lh.size = w.size() - lh.offset - lh.size + if lh.size < 56 { + w.lhsize++ // length encoded into kind tag + } else { + w.lhsize += 1 + intsize(uint64(lh.size)) + } +} + +func (w *encbuf) size() int { + return len(w.str) + w.lhsize +} + +func (w *encbuf) toBytes() []byte { + out := make([]byte, w.size()) + strpos := 0 + pos := 0 + for _, head := range w.lheads { + // write string data before header + n := copy(out[pos:], w.str[strpos:head.offset]) + pos += n + strpos += n + // write the header + enc := head.encode(out[pos:]) + pos += len(enc) + } + // copy string data after the last list header + copy(out[pos:], w.str[strpos:]) + return out +} + +func (w *encbuf) toWriter(out io.Writer) (err error) { + strpos := 0 + for _, head := range w.lheads { + // write string data before header + if head.offset-strpos > 0 { + n, err := out.Write(w.str[strpos:head.offset]) + strpos += n + if err != nil { + return err + } + } + // write the header + enc := head.encode(w.sizebuf) + if _, err = out.Write(enc); err != nil { + return err + } + } + if strpos < len(w.str) { + // write string data after the last list header + _, err = out.Write(w.str[strpos:]) + } + return err +} + +// encReader is the io.Reader returned by EncodeToReader. +// It releases its encbuf at EOF. +type encReader struct { + buf *encbuf // the buffer we're reading from. this is nil when we're at EOF. + lhpos int // index of list header that we're reading + strpos int // current position in string buffer + piece []byte // next piece to be read +} + +func (r *encReader) Read(b []byte) (n int, err error) { + for { + if r.piece = r.next(); r.piece == nil { + // Put the encode buffer back into the pool at EOF when it + // is first encountered. Subsequent calls still return EOF + // as the error but the buffer is no longer valid. + if r.buf != nil { + encbufPool.Put(r.buf) + r.buf = nil + } + return n, io.EOF + } + nn := copy(b[n:], r.piece) + n += nn + if nn < len(r.piece) { + // piece didn't fit, see you next time. + r.piece = r.piece[nn:] + return n, nil + } + r.piece = nil + } +} + +// next returns the next piece of data to be read. +// it returns nil at EOF. +func (r *encReader) next() []byte { + switch { + case r.buf == nil: + return nil + + case r.piece != nil: + // There is still data available for reading. + return r.piece + + case r.lhpos < len(r.buf.lheads): + // We're before the last list header. + head := r.buf.lheads[r.lhpos] + sizebefore := head.offset - r.strpos + if sizebefore > 0 { + // String data before header. + p := r.buf.str[r.strpos:head.offset] + r.strpos += sizebefore + return p + } + r.lhpos++ + return head.encode(r.buf.sizebuf) + + case r.strpos < len(r.buf.str): + // String data at the end, after all list headers. + p := r.buf.str[r.strpos:] + r.strpos = len(r.buf.str) + return p + + default: + return nil + } +} + +var ( + encoderInterface = reflect.TypeOf(new(Encoder)).Elem() + big0 = big.NewInt(0) +) + +// makeWriter creates a writer function for the given type. +func makeWriter(typ reflect.Type, ts tags) (writer, error) { + kind := typ.Kind() + switch { + case typ == rawValueType: + return writeRawValue, nil + case typ.AssignableTo(reflect.PtrTo(bigInt)): + return writeBigIntPtr, nil + case typ.AssignableTo(bigInt): + return writeBigIntNoPtr, nil + case kind == reflect.Ptr: + return makePtrWriter(typ, ts) + case reflect.PtrTo(typ).Implements(encoderInterface): + return makeEncoderWriter(typ), nil + case isUint(kind): + return writeUint, nil + case kind == reflect.Bool: + return writeBool, nil + case kind == reflect.String: + return writeString, nil + case kind == reflect.Slice && isByte(typ.Elem()): + return writeBytes, nil + case kind == reflect.Array && isByte(typ.Elem()): + return writeByteArray, nil + case kind == reflect.Slice || kind == reflect.Array: + return makeSliceWriter(typ, ts) + case kind == reflect.Struct: + return makeStructWriter(typ) + case kind == reflect.Interface: + return writeInterface, nil + default: + return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) + } +} + +func isByte(typ reflect.Type) bool { + return typ.Kind() == reflect.Uint8 && !typ.Implements(encoderInterface) +} + +func writeRawValue(val reflect.Value, w *encbuf) error { + w.str = append(w.str, val.Bytes()...) + return nil +} + +func writeUint(val reflect.Value, w *encbuf) error { + i := val.Uint() + if i == 0 { + w.str = append(w.str, 0x80) + } else if i < 128 { + // fits single byte + w.str = append(w.str, byte(i)) + } else { + // TODO: encode int to w.str directly + s := putint(w.sizebuf[1:], i) + w.sizebuf[0] = 0x80 + byte(s) + w.str = append(w.str, w.sizebuf[:s+1]...) + } + return nil +} + +func writeBool(val reflect.Value, w *encbuf) error { + if val.Bool() { + w.str = append(w.str, 0x01) + } else { + w.str = append(w.str, 0x80) + } + return nil +} + +func writeBigIntPtr(val reflect.Value, w *encbuf) error { + ptr := val.Interface().(*big.Int) + if ptr == nil { + w.str = append(w.str, 0x80) + return nil + } + return writeBigInt(ptr, w) +} + +func writeBigIntNoPtr(val reflect.Value, w *encbuf) error { + i := val.Interface().(big.Int) + return writeBigInt(&i, w) +} + +func writeBigInt(i *big.Int, w *encbuf) error { + if cmp := i.Cmp(big0); cmp == -1 { + return fmt.Errorf("rlp: cannot encode negative *big.Int") + } else if cmp == 0 { + w.str = append(w.str, 0x80) + } else { + w.encodeString(i.Bytes()) + } + return nil +} + +func writeBytes(val reflect.Value, w *encbuf) error { + w.encodeString(val.Bytes()) + return nil +} + +func writeByteArray(val reflect.Value, w *encbuf) error { + if !val.CanAddr() { + // Slice requires the value to be addressable. + // Make it addressable by copying. + copy := reflect.New(val.Type()).Elem() + copy.Set(val) + val = copy + } + size := val.Len() + slice := val.Slice(0, size).Bytes() + w.encodeString(slice) + return nil +} + +func writeString(val reflect.Value, w *encbuf) error { + s := val.String() + if len(s) == 1 && s[0] <= 0x7f { + // fits single byte, no string header + w.str = append(w.str, s[0]) + } else { + w.encodeStringHeader(len(s)) + w.str = append(w.str, s...) + } + return nil +} + +func writeInterface(val reflect.Value, w *encbuf) error { + if val.IsNil() { + // Write empty list. This is consistent with the previous RLP + // encoder that we had and should therefore avoid any + // problems. + w.str = append(w.str, 0xC0) + return nil + } + eval := val.Elem() + writer, err := cachedWriter(eval.Type()) + if err != nil { + return err + } + return writer(eval, w) +} + +func makeSliceWriter(typ reflect.Type, ts tags) (writer, error) { + etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) + if etypeinfo.writerErr != nil { + return nil, etypeinfo.writerErr + } + writer := func(val reflect.Value, w *encbuf) error { + if !ts.tail { + defer w.listEnd(w.list()) + } + vlen := val.Len() + for i := 0; i < vlen; i++ { + if err := etypeinfo.writer(val.Index(i), w); err != nil { + return err + } + } + return nil + } + return writer, nil +} + +func makeStructWriter(typ reflect.Type) (writer, error) { + fields, err := structFields(typ) + if err != nil { + return nil, err + } + for _, f := range fields { + if f.info.writerErr != nil { + return nil, structFieldError{typ, f.index, f.info.writerErr} + } + } + writer := func(val reflect.Value, w *encbuf) error { + lh := w.list() + for _, f := range fields { + if err := f.info.writer(val.Field(f.index), w); err != nil { + return err + } + } + w.listEnd(lh) + return nil + } + return writer, nil +} + +func makePtrWriter(typ reflect.Type, ts tags) (writer, error) { + etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) + if etypeinfo.writerErr != nil { + return nil, etypeinfo.writerErr + } + // Determine how to encode nil pointers. + var nilKind Kind + if ts.nilOK { + nilKind = ts.nilKind // use struct tag if provided + } else { + nilKind = defaultNilKind(typ.Elem()) + } + + writer := func(val reflect.Value, w *encbuf) error { + if val.IsNil() { + if nilKind == String { + w.str = append(w.str, 0x80) + } else { + w.listEnd(w.list()) + } + return nil + } + return etypeinfo.writer(val.Elem(), w) + } + return writer, nil +} + +func makeEncoderWriter(typ reflect.Type) writer { + if typ.Implements(encoderInterface) { + return func(val reflect.Value, w *encbuf) error { + return val.Interface().(Encoder).EncodeRLP(w) + } + } + w := func(val reflect.Value, w *encbuf) error { + if !val.CanAddr() { + // package json simply doesn't call MarshalJSON for this case, but encodes the + // value as if it didn't implement the interface. We don't want to handle it that + // way. + return fmt.Errorf("rlp: unadressable value of type %v, EncodeRLP is pointer method", val.Type()) + } + return val.Addr().Interface().(Encoder).EncodeRLP(w) + } + return w +} + +// putint writes i to the beginning of b in big endian byte +// order, using the least number of bytes needed to represent i. +func putint(b []byte, i uint64) (size int) { + switch { + case i < (1 << 8): + b[0] = byte(i) + return 1 + case i < (1 << 16): + b[0] = byte(i >> 8) + b[1] = byte(i) + return 2 + case i < (1 << 24): + b[0] = byte(i >> 16) + b[1] = byte(i >> 8) + b[2] = byte(i) + return 3 + case i < (1 << 32): + b[0] = byte(i >> 24) + b[1] = byte(i >> 16) + b[2] = byte(i >> 8) + b[3] = byte(i) + return 4 + case i < (1 << 40): + b[0] = byte(i >> 32) + b[1] = byte(i >> 24) + b[2] = byte(i >> 16) + b[3] = byte(i >> 8) + b[4] = byte(i) + return 5 + case i < (1 << 48): + b[0] = byte(i >> 40) + b[1] = byte(i >> 32) + b[2] = byte(i >> 24) + b[3] = byte(i >> 16) + b[4] = byte(i >> 8) + b[5] = byte(i) + return 6 + case i < (1 << 56): + b[0] = byte(i >> 48) + b[1] = byte(i >> 40) + b[2] = byte(i >> 32) + b[3] = byte(i >> 24) + b[4] = byte(i >> 16) + b[5] = byte(i >> 8) + b[6] = byte(i) + return 7 + default: + b[0] = byte(i >> 56) + b[1] = byte(i >> 48) + b[2] = byte(i >> 40) + b[3] = byte(i >> 32) + b[4] = byte(i >> 24) + b[5] = byte(i >> 16) + b[6] = byte(i >> 8) + b[7] = byte(i) + return 8 + } +} + +// intsize computes the minimum number of bytes required to store i. +func intsize(i uint64) (size int) { + for size = 1; ; size++ { + if i >>= 8; i == 0 { + return size + } + } +} diff --git a/bsc/rlp/encode_test.go b/bsc/rlp/encode_test.go new file mode 100644 index 0000000000..f32a239643 --- /dev/null +++ b/bsc/rlp/encode_test.go @@ -0,0 +1,402 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "bytes" + "errors" + "fmt" + "io" + "math/big" + "sync" + "testing" +) + +type testEncoder struct { + err error +} + +func (e *testEncoder) EncodeRLP(w io.Writer) error { + if e == nil { + panic("EncodeRLP called on nil value") + } + if e.err != nil { + return e.err + } else { + w.Write([]byte{0, 1, 0, 1, 0, 1, 0, 1, 0, 1}) + } + return nil +} + +type testEncoderValueMethod struct{} + +func (e testEncoderValueMethod) EncodeRLP(w io.Writer) error { + w.Write([]byte{0xFA, 0xFE, 0xF0}) + return nil +} + +type byteEncoder byte + +func (e byteEncoder) EncodeRLP(w io.Writer) error { + w.Write(EmptyList) + return nil +} + +type undecodableEncoder func() + +func (f undecodableEncoder) EncodeRLP(w io.Writer) error { + w.Write([]byte{0xF5, 0xF5, 0xF5}) + return nil +} + +type encodableReader struct { + A, B uint +} + +func (e *encodableReader) Read(b []byte) (int, error) { + panic("called") +} + +type namedByteType byte + +var ( + _ = Encoder(&testEncoder{}) + _ = Encoder(byteEncoder(0)) + + reader io.Reader = &encodableReader{1, 2} +) + +type encTest struct { + val interface{} + output, error string +} + +var encTests = []encTest{ + // booleans + {val: true, output: "01"}, + {val: false, output: "80"}, + + // integers + {val: uint32(0), output: "80"}, + {val: uint32(127), output: "7F"}, + {val: uint32(128), output: "8180"}, + {val: uint32(256), output: "820100"}, + {val: uint32(1024), output: "820400"}, + {val: uint32(0xFFFFFF), output: "83FFFFFF"}, + {val: uint32(0xFFFFFFFF), output: "84FFFFFFFF"}, + {val: uint64(0xFFFFFFFF), output: "84FFFFFFFF"}, + {val: uint64(0xFFFFFFFFFF), output: "85FFFFFFFFFF"}, + {val: uint64(0xFFFFFFFFFFFF), output: "86FFFFFFFFFFFF"}, + {val: uint64(0xFFFFFFFFFFFFFF), output: "87FFFFFFFFFFFFFF"}, + {val: uint64(0xFFFFFFFFFFFFFFFF), output: "88FFFFFFFFFFFFFFFF"}, + + // big integers (should match uint for small values) + {val: big.NewInt(0), output: "80"}, + {val: big.NewInt(1), output: "01"}, + {val: big.NewInt(127), output: "7F"}, + {val: big.NewInt(128), output: "8180"}, + {val: big.NewInt(256), output: "820100"}, + {val: big.NewInt(1024), output: "820400"}, + {val: big.NewInt(0xFFFFFF), output: "83FFFFFF"}, + {val: big.NewInt(0xFFFFFFFF), output: "84FFFFFFFF"}, + {val: big.NewInt(0xFFFFFFFFFF), output: "85FFFFFFFFFF"}, + {val: big.NewInt(0xFFFFFFFFFFFF), output: "86FFFFFFFFFFFF"}, + {val: big.NewInt(0xFFFFFFFFFFFFFF), output: "87FFFFFFFFFFFFFF"}, + { + val: big.NewInt(0).SetBytes(unhex("102030405060708090A0B0C0D0E0F2")), + output: "8F102030405060708090A0B0C0D0E0F2", + }, + { + val: big.NewInt(0).SetBytes(unhex("0100020003000400050006000700080009000A000B000C000D000E01")), + output: "9C0100020003000400050006000700080009000A000B000C000D000E01", + }, + { + val: big.NewInt(0).SetBytes(unhex("010000000000000000000000000000000000000000000000000000000000000000")), + output: "A1010000000000000000000000000000000000000000000000000000000000000000", + }, + + // non-pointer big.Int + {val: *big.NewInt(0), output: "80"}, + {val: *big.NewInt(0xFFFFFF), output: "83FFFFFF"}, + + // negative ints are not supported + {val: big.NewInt(-1), error: "rlp: cannot encode negative *big.Int"}, + + // byte slices, strings + {val: []byte{}, output: "80"}, + {val: []byte{0x7E}, output: "7E"}, + {val: []byte{0x7F}, output: "7F"}, + {val: []byte{0x80}, output: "8180"}, + {val: []byte{1, 2, 3}, output: "83010203"}, + + {val: []namedByteType{1, 2, 3}, output: "83010203"}, + {val: [...]namedByteType{1, 2, 3}, output: "83010203"}, + + {val: "", output: "80"}, + {val: "\x7E", output: "7E"}, + {val: "\x7F", output: "7F"}, + {val: "\x80", output: "8180"}, + {val: "dog", output: "83646F67"}, + { + val: "Lorem ipsum dolor sit amet, consectetur adipisicing eli", + output: "B74C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E7365637465747572206164697069736963696E6720656C69", + }, + { + val: "Lorem ipsum dolor sit amet, consectetur adipisicing elit", + output: "B8384C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E7365637465747572206164697069736963696E6720656C6974", + }, + { + val: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur mauris magna, suscipit sed vehicula non, iaculis faucibus tortor. Proin suscipit ultricies malesuada. Duis tortor elit, dictum quis tristique eu, ultrices at risus. Morbi a est imperdiet mi ullamcorper aliquet suscipit nec lorem. Aenean quis leo mollis, vulputate elit varius, consequat enim. Nulla ultrices turpis justo, et posuere urna consectetur nec. Proin non convallis metus. Donec tempor ipsum in mauris congue sollicitudin. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse convallis sem vel massa faucibus, eget lacinia lacus tempor. Nulla quis ultricies purus. Proin auctor rhoncus nibh condimentum mollis. Aliquam consequat enim at metus luctus, a eleifend purus egestas. Curabitur at nibh metus. Nam bibendum, neque at auctor tristique, lorem libero aliquet arcu, non interdum tellus lectus sit amet eros. Cras rhoncus, metus ac ornare cursus, dolor justo ultrices metus, at ullamcorper volutpat", + output: "B904004C6F72656D20697073756D20646F6C6F722073697420616D65742C20636F6E73656374657475722061646970697363696E6720656C69742E20437572616269747572206D6175726973206D61676E612C20737573636970697420736564207665686963756C61206E6F6E2C20696163756C697320666175636962757320746F72746F722E2050726F696E20737573636970697420756C74726963696573206D616C6573756164612E204475697320746F72746F7220656C69742C2064696374756D2071756973207472697374697175652065752C20756C7472696365732061742072697375732E204D6F72626920612065737420696D70657264696574206D6920756C6C616D636F7270657220616C6971756574207375736369706974206E6563206C6F72656D2E2041656E65616E2071756973206C656F206D6F6C6C69732C2076756C70757461746520656C6974207661726975732C20636F6E73657175617420656E696D2E204E756C6C6120756C74726963657320747572706973206A7573746F2C20657420706F73756572652075726E6120636F6E7365637465747572206E65632E2050726F696E206E6F6E20636F6E76616C6C6973206D657475732E20446F6E65632074656D706F7220697073756D20696E206D617572697320636F6E67756520736F6C6C696369747564696E2E20566573746962756C756D20616E746520697073756D207072696D697320696E206661756369627573206F726369206C756374757320657420756C74726963657320706F737565726520637562696C69612043757261653B2053757370656E646973736520636F6E76616C6C69732073656D2076656C206D617373612066617563696275732C2065676574206C6163696E6961206C616375732074656D706F722E204E756C6C61207175697320756C747269636965732070757275732E2050726F696E20617563746F722072686F6E637573206E69626820636F6E64696D656E74756D206D6F6C6C69732E20416C697175616D20636F6E73657175617420656E696D206174206D65747573206C75637475732C206120656C656966656E6420707572757320656765737461732E20437572616269747572206174206E696268206D657475732E204E616D20626962656E64756D2C206E6571756520617420617563746F72207472697374697175652C206C6F72656D206C696265726F20616C697175657420617263752C206E6F6E20696E74657264756D2074656C6C7573206C65637475732073697420616D65742065726F732E20437261732072686F6E6375732C206D65747573206163206F726E617265206375727375732C20646F6C6F72206A7573746F20756C747269636573206D657475732C20617420756C6C616D636F7270657220766F6C7574706174", + }, + + // slices + {val: []uint{}, output: "C0"}, + {val: []uint{1, 2, 3}, output: "C3010203"}, + { + // [ [], [[]], [ [], [[]] ] ] + val: []interface{}{[]interface{}{}, [][]interface{}{{}}, []interface{}{[]interface{}{}, [][]interface{}{{}}}}, + output: "C7C0C1C0C3C0C1C0", + }, + { + val: []string{"aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", "kkk", "lll", "mmm", "nnn", "ooo"}, + output: "F83C836161618362626283636363836464648365656583666666836767678368686883696969836A6A6A836B6B6B836C6C6C836D6D6D836E6E6E836F6F6F", + }, + { + val: []interface{}{uint(1), uint(0xFFFFFF), []interface{}{[]uint{4, 5, 5}}, "abc"}, + output: "CE0183FFFFFFC4C304050583616263", + }, + { + val: [][]string{ + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + {"asdf", "qwer", "zxcv"}, + }, + output: "F90200CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376CF84617364668471776572847A786376", + }, + + // RawValue + {val: RawValue(unhex("01")), output: "01"}, + {val: RawValue(unhex("82FFFF")), output: "82FFFF"}, + {val: []RawValue{unhex("01"), unhex("02")}, output: "C20102"}, + + // structs + {val: simplestruct{}, output: "C28080"}, + {val: simplestruct{A: 3, B: "foo"}, output: "C50383666F6F"}, + {val: &recstruct{5, nil}, output: "C205C0"}, + {val: &recstruct{5, &recstruct{4, &recstruct{3, nil}}}, output: "C605C404C203C0"}, + {val: &tailRaw{A: 1, Tail: []RawValue{unhex("02"), unhex("03")}}, output: "C3010203"}, + {val: &tailRaw{A: 1, Tail: []RawValue{unhex("02")}}, output: "C20102"}, + {val: &tailRaw{A: 1, Tail: []RawValue{}}, output: "C101"}, + {val: &tailRaw{A: 1, Tail: nil}, output: "C101"}, + {val: &hasIgnoredField{A: 1, B: 2, C: 3}, output: "C20103"}, + {val: &intField{X: 3}, error: "rlp: type int is not RLP-serializable (struct field rlp.intField.X)"}, + + // nil + {val: (*uint)(nil), output: "80"}, + {val: (*string)(nil), output: "80"}, + {val: (*[]byte)(nil), output: "80"}, + {val: (*[10]byte)(nil), output: "80"}, + {val: (*big.Int)(nil), output: "80"}, + {val: (*[]string)(nil), output: "C0"}, + {val: (*[10]string)(nil), output: "C0"}, + {val: (*[]interface{})(nil), output: "C0"}, + {val: (*[]struct{ uint })(nil), output: "C0"}, + {val: (*interface{})(nil), output: "C0"}, + + // nil struct fields + { + val: struct { + X *[]byte + }{}, + output: "C180", + }, + { + val: struct { + X *[2]byte + }{}, + output: "C180", + }, + { + val: struct { + X *uint64 + }{}, + output: "C180", + }, + { + val: struct { + X *uint64 `rlp:"nilList"` + }{}, + output: "C1C0", + }, + { + val: struct { + X *[]uint64 + }{}, + output: "C1C0", + }, + { + val: struct { + X *[]uint64 `rlp:"nilString"` + }{}, + output: "C180", + }, + + // interfaces + {val: []io.Reader{reader}, output: "C3C20102"}, // the contained value is a struct + + // Encoder + {val: (*testEncoder)(nil), output: "C0"}, + {val: &testEncoder{}, output: "00010001000100010001"}, + {val: &testEncoder{errors.New("test error")}, error: "test error"}, + {val: struct{ E testEncoderValueMethod }{}, output: "C3FAFEF0"}, + {val: struct{ E *testEncoderValueMethod }{}, output: "C1C0"}, + + // Verify that the Encoder interface works for unsupported types like func(). + {val: undecodableEncoder(func() {}), output: "F5F5F5"}, + + // Verify that pointer method testEncoder.EncodeRLP is called for + // addressable non-pointer values. + {val: &struct{ TE testEncoder }{testEncoder{}}, output: "CA00010001000100010001"}, + {val: &struct{ TE testEncoder }{testEncoder{errors.New("test error")}}, error: "test error"}, + + // Verify the error for non-addressable non-pointer Encoder. + {val: testEncoder{}, error: "rlp: unadressable value of type rlp.testEncoder, EncodeRLP is pointer method"}, + + // Verify Encoder takes precedence over []byte. + {val: []byteEncoder{0, 1, 2, 3, 4}, output: "C5C0C0C0C0C0"}, +} + +func runEncTests(t *testing.T, f func(val interface{}) ([]byte, error)) { + for i, test := range encTests { + output, err := f(test.val) + if err != nil && test.error == "" { + t.Errorf("test %d: unexpected error: %v\nvalue %#v\ntype %T", + i, err, test.val, test.val) + continue + } + if test.error != "" && fmt.Sprint(err) != test.error { + t.Errorf("test %d: error mismatch\ngot %v\nwant %v\nvalue %#v\ntype %T", + i, err, test.error, test.val, test.val) + continue + } + if err == nil && !bytes.Equal(output, unhex(test.output)) { + t.Errorf("test %d: output mismatch:\ngot %X\nwant %s\nvalue %#v\ntype %T", + i, output, test.output, test.val, test.val) + } + } +} + +func TestEncode(t *testing.T) { + runEncTests(t, func(val interface{}) ([]byte, error) { + b := new(bytes.Buffer) + err := Encode(b, val) + return b.Bytes(), err + }) +} + +func TestEncodeToBytes(t *testing.T) { + runEncTests(t, EncodeToBytes) +} + +func TestEncodeToReader(t *testing.T) { + runEncTests(t, func(val interface{}) ([]byte, error) { + _, r, err := EncodeToReader(val) + if err != nil { + return nil, err + } + return io.ReadAll(r) + }) +} + +func TestEncodeToReaderPiecewise(t *testing.T) { + runEncTests(t, func(val interface{}) ([]byte, error) { + size, r, err := EncodeToReader(val) + if err != nil { + return nil, err + } + + // read output piecewise + output := make([]byte, size) + for start, end := 0, 0; start < size; start = end { + if remaining := size - start; remaining < 3 { + end += remaining + } else { + end = start + 3 + } + n, err := r.Read(output[start:end]) + end = start + n + if err == io.EOF { + break + } else if err != nil { + return nil, err + } + } + return output, nil + }) +} + +// This is a regression test verifying that encReader +// returns its encbuf to the pool only once. +func TestEncodeToReaderReturnToPool(t *testing.T) { + buf := make([]byte, 50) + wg := new(sync.WaitGroup) + for i := 0; i < 5; i++ { + wg.Add(1) + go func() { + for i := 0; i < 1000; i++ { + _, r, _ := EncodeToReader("foo") + io.ReadAll(r) + r.Read(buf) + r.Read(buf) + r.Read(buf) + r.Read(buf) + } + wg.Done() + }() + } + wg.Wait() +} diff --git a/bsc/rlp/encoder_example_test.go b/bsc/rlp/encoder_example_test.go new file mode 100644 index 0000000000..42c1c5c890 --- /dev/null +++ b/bsc/rlp/encoder_example_test.go @@ -0,0 +1,46 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "fmt" + "io" +) + +type MyCoolType struct { + Name string + a, b uint +} + +// EncodeRLP writes x as RLP list [a, b] that omits the Name field. +func (x *MyCoolType) EncodeRLP(w io.Writer) (err error) { + return Encode(w, []uint{x.a, x.b}) +} + +func ExampleEncoder() { + var t *MyCoolType // t is nil pointer to MyCoolType + bytes, _ := EncodeToBytes(t) + fmt.Printf("%v → %X\n", t, bytes) + + t = &MyCoolType{Name: "foobar", a: 5, b: 6} + bytes, _ = EncodeToBytes(t) + fmt.Printf("%v → %X\n", t, bytes) + + // Output: + // → C0 + // &{foobar 5 6} → C20506 +} diff --git a/bsc/rlp/raw.go b/bsc/rlp/raw.go new file mode 100644 index 0000000000..2b3f328f66 --- /dev/null +++ b/bsc/rlp/raw.go @@ -0,0 +1,156 @@ +// Copyright 2015 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "io" + "reflect" +) + +// RawValue represents an encoded RLP value and can be used to delay +// RLP decoding or to precompute an encoding. Note that the decoder does +// not verify whether the content of RawValues is valid RLP. +type RawValue []byte + +var rawValueType = reflect.TypeOf(RawValue{}) + +// ListSize returns the encoded size of an RLP list with the given +// content size. +func ListSize(contentSize uint64) uint64 { + return uint64(headsize(contentSize)) + contentSize +} + +// Split returns the content of first RLP value and any +// bytes after the value as subslices of b. +func Split(b []byte) (k Kind, content, rest []byte, err error) { + k, ts, cs, err := readKind(b) + if err != nil { + return 0, nil, b, err + } + return k, b[ts : ts+cs], b[ts+cs:], nil +} + +// SplitString splits b into the content of an RLP string +// and any remaining bytes after the string. +func SplitString(b []byte) (content, rest []byte, err error) { + k, content, rest, err := Split(b) + if err != nil { + return nil, b, err + } + if k == List { + return nil, b, ErrExpectedString + } + return content, rest, nil +} + +// SplitList splits b into the content of a list and any remaining +// bytes after the list. +func SplitList(b []byte) (content, rest []byte, err error) { + k, content, rest, err := Split(b) + if err != nil { + return nil, b, err + } + if k != List { + return nil, b, ErrExpectedList + } + return content, rest, nil +} + +// CountValues counts the number of encoded values in b. +func CountValues(b []byte) (int, error) { + i := 0 + for ; len(b) > 0; i++ { + _, tagsize, size, err := readKind(b) + if err != nil { + return 0, err + } + b = b[tagsize+size:] + } + return i, nil +} + +func readKind(buf []byte) (k Kind, tagsize, contentsize uint64, err error) { + if len(buf) == 0 { + return 0, 0, 0, io.ErrUnexpectedEOF + } + b := buf[0] + switch { + case b < 0x80: + k = Byte + tagsize = 0 + contentsize = 1 + case b < 0xB8: + k = String + tagsize = 1 + contentsize = uint64(b - 0x80) + // Reject strings that should've been single bytes. + if contentsize == 1 && len(buf) > 1 && buf[1] < 128 { + return 0, 0, 0, ErrCanonSize + } + case b < 0xC0: + k = String + tagsize = uint64(b-0xB7) + 1 + contentsize, err = readSize(buf[1:], b-0xB7) + case b < 0xF8: + k = List + tagsize = 1 + contentsize = uint64(b - 0xC0) + default: + k = List + tagsize = uint64(b-0xF7) + 1 + contentsize, err = readSize(buf[1:], b-0xF7) + } + if err != nil { + return 0, 0, 0, err + } + // Reject values larger than the input slice. + if contentsize > uint64(len(buf))-tagsize { + return 0, 0, 0, ErrValueTooLarge + } + return k, tagsize, contentsize, err +} + +func readSize(b []byte, slen byte) (uint64, error) { + if int(slen) > len(b) { + return 0, io.ErrUnexpectedEOF + } + var s uint64 + switch slen { + case 1: + s = uint64(b[0]) + case 2: + s = uint64(b[0])<<8 | uint64(b[1]) + case 3: + s = uint64(b[0])<<16 | uint64(b[1])<<8 | uint64(b[2]) + case 4: + s = uint64(b[0])<<24 | uint64(b[1])<<16 | uint64(b[2])<<8 | uint64(b[3]) + case 5: + s = uint64(b[0])<<32 | uint64(b[1])<<24 | uint64(b[2])<<16 | uint64(b[3])<<8 | uint64(b[4]) + case 6: + s = uint64(b[0])<<40 | uint64(b[1])<<32 | uint64(b[2])<<24 | uint64(b[3])<<16 | uint64(b[4])<<8 | uint64(b[5]) + case 7: + s = uint64(b[0])<<48 | uint64(b[1])<<40 | uint64(b[2])<<32 | uint64(b[3])<<24 | uint64(b[4])<<16 | uint64(b[5])<<8 | uint64(b[6]) + case 8: + s = uint64(b[0])<<56 | uint64(b[1])<<48 | uint64(b[2])<<40 | uint64(b[3])<<32 | uint64(b[4])<<24 | uint64(b[5])<<16 | uint64(b[6])<<8 | uint64(b[7]) + } + // Reject sizes < 56 (shouldn't have separate size) and sizes with + // leading zero bytes. + if s < 56 || b[0] == 0 { + return 0, ErrCanonSize + } + return s, nil +} diff --git a/bsc/rlp/raw_test.go b/bsc/rlp/raw_test.go new file mode 100644 index 0000000000..2aad042100 --- /dev/null +++ b/bsc/rlp/raw_test.go @@ -0,0 +1,196 @@ +// Copyright 2015 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "bytes" + "io" + "reflect" + "testing" +) + +func TestCountValues(t *testing.T) { + tests := []struct { + input string // note: spaces in input are stripped by unhex + count int + err error + }{ + // simple cases + {"", 0, nil}, + {"00", 1, nil}, + {"80", 1, nil}, + {"C0", 1, nil}, + {"01 02 03", 3, nil}, + {"01 C406070809 02", 3, nil}, + {"820101 820202 8403030303 04", 4, nil}, + + // size errors + {"8142", 0, ErrCanonSize}, + {"01 01 8142", 0, ErrCanonSize}, + {"02 84020202", 0, ErrValueTooLarge}, + + { + input: "A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", + count: 2, + }, + } + for i, test := range tests { + count, err := CountValues(unhex(test.input)) + if count != test.count { + t.Errorf("test %d: count mismatch, got %d want %d\ninput: %s", i, count, test.count, test.input) + } + if !reflect.DeepEqual(err, test.err) { + t.Errorf("test %d: err mismatch, got %q want %q\ninput: %s", i, err, test.err, test.input) + } + } +} + +func TestSplitTypes(t *testing.T) { + if _, _, err := SplitString(unhex("C100")); err != ErrExpectedString { + t.Errorf("SplitString returned %q, want %q", err, ErrExpectedString) + } + if _, _, err := SplitList(unhex("01")); err != ErrExpectedList { + t.Errorf("SplitString returned %q, want %q", err, ErrExpectedList) + } + if _, _, err := SplitList(unhex("81FF")); err != ErrExpectedList { + t.Errorf("SplitString returned %q, want %q", err, ErrExpectedList) + } +} + +func TestSplit(t *testing.T) { + tests := []struct { + input string + kind Kind + val, rest string + err error + }{ + {input: "01FFFF", kind: Byte, val: "01", rest: "FFFF"}, + {input: "80FFFF", kind: String, val: "", rest: "FFFF"}, + {input: "C3010203", kind: List, val: "010203"}, + + // errors + {input: "", err: io.ErrUnexpectedEOF}, + + {input: "8141", err: ErrCanonSize, rest: "8141"}, + {input: "B800", err: ErrCanonSize, rest: "B800"}, + {input: "B802FFFF", err: ErrCanonSize, rest: "B802FFFF"}, + {input: "B90000", err: ErrCanonSize, rest: "B90000"}, + {input: "B90055", err: ErrCanonSize, rest: "B90055"}, + {input: "BA0002FFFF", err: ErrCanonSize, rest: "BA0002FFFF"}, + {input: "F800", err: ErrCanonSize, rest: "F800"}, + {input: "F90000", err: ErrCanonSize, rest: "F90000"}, + {input: "F90055", err: ErrCanonSize, rest: "F90055"}, + {input: "FA0002FFFF", err: ErrCanonSize, rest: "FA0002FFFF"}, + + {input: "81", err: ErrValueTooLarge, rest: "81"}, + {input: "8501010101", err: ErrValueTooLarge, rest: "8501010101"}, + {input: "C60607080902", err: ErrValueTooLarge, rest: "C60607080902"}, + + // size check overflow + {input: "BFFFFFFFFFFFFFFFFF", err: ErrValueTooLarge, rest: "BFFFFFFFFFFFFFFFFF"}, + {input: "FFFFFFFFFFFFFFFFFF", err: ErrValueTooLarge, rest: "FFFFFFFFFFFFFFFFFF"}, + + { + input: "B838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + err: ErrValueTooLarge, + rest: "B838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + }, + { + input: "F838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + err: ErrValueTooLarge, + rest: "F838FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + }, + + // a few bigger values, just for kicks + { + input: "F839FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + kind: List, + val: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + rest: "", + }, + { + input: "F90211A060EF29F20CC1007AE6E9530AEE16F4B31F8F1769A2D1264EC995C6D1241868D6A07C62AB8AC9838F5F5877B20BB37B387BC2106E97A3D52172CBEDB5EE17C36008A00EAB6B7324AADC0F6047C6AFC8229F09F7CF451B51D67C8DFB08D49BA8C3C626A04453343B2F3A6E42FCF87948F88AF7C8FC16D0C2735CBA7F026836239AB2C15FA024635C7291C882CE4C0763760C1A362DFC3FFCD802A55722236DE058D74202ACA0A220C808DE10F55E40AB25255201CFF009EA181D3906638E944EE2BF34049984A08D325AB26796F1CCB470F69C0F842501DC35D368A0C2575B2D243CFD1E8AB0FDA0B5298FF60DA5069463D610513C9F04F24051348391A143AFFAB7197DFACDEA72A02D2A7058A4463F8FB69378369E11EF33AE3252E2DB86CB545B36D3C26DDECE5AA0888F97BCA8E0BD83DC5B3B91CFF5FAF2F66F9501010682D67EF4A3B4E66115FBA0E8175A60C93BE9ED02921958F0EA55DA0FB5E4802AF5846147BAD92BC2D8AF26A08B3376FF433F3A4250FA64B7F804004CAC5807877D91C4427BD1CD05CF912ED8A09B32EF0F03BD13C37FF950C0CCCEFCCDD6669F2E7F2AA5CB859928E84E29763EA09BBA5E46610C8C8B1F8E921E5691BF8C7E40D75825D5EA3217AA9C3A8A355F39A0EEB95BC78251CCCEC54A97F19755C4A59A293544EEE6119AFA50531211E53C4FA00B6E86FE150BF4A9E0FEEE9C90F5465E617A861BB5E357F942881EE762212E2580", + kind: List, + val: "A060EF29F20CC1007AE6E9530AEE16F4B31F8F1769A2D1264EC995C6D1241868D6A07C62AB8AC9838F5F5877B20BB37B387BC2106E97A3D52172CBEDB5EE17C36008A00EAB6B7324AADC0F6047C6AFC8229F09F7CF451B51D67C8DFB08D49BA8C3C626A04453343B2F3A6E42FCF87948F88AF7C8FC16D0C2735CBA7F026836239AB2C15FA024635C7291C882CE4C0763760C1A362DFC3FFCD802A55722236DE058D74202ACA0A220C808DE10F55E40AB25255201CFF009EA181D3906638E944EE2BF34049984A08D325AB26796F1CCB470F69C0F842501DC35D368A0C2575B2D243CFD1E8AB0FDA0B5298FF60DA5069463D610513C9F04F24051348391A143AFFAB7197DFACDEA72A02D2A7058A4463F8FB69378369E11EF33AE3252E2DB86CB545B36D3C26DDECE5AA0888F97BCA8E0BD83DC5B3B91CFF5FAF2F66F9501010682D67EF4A3B4E66115FBA0E8175A60C93BE9ED02921958F0EA55DA0FB5E4802AF5846147BAD92BC2D8AF26A08B3376FF433F3A4250FA64B7F804004CAC5807877D91C4427BD1CD05CF912ED8A09B32EF0F03BD13C37FF950C0CCCEFCCDD6669F2E7F2AA5CB859928E84E29763EA09BBA5E46610C8C8B1F8E921E5691BF8C7E40D75825D5EA3217AA9C3A8A355F39A0EEB95BC78251CCCEC54A97F19755C4A59A293544EEE6119AFA50531211E53C4FA00B6E86FE150BF4A9E0FEEE9C90F5465E617A861BB5E357F942881EE762212E2580", + rest: "", + }, + { + input: "F877A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", + kind: List, + val: "A12000BF49F440A1CD0527E4D06E2765654C0F56452257516D793A9B8D604DCFDF2AB853F851808D10000000000000000000000000A056E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421A0C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", + rest: "", + }, + } + + for i, test := range tests { + kind, val, rest, err := Split(unhex(test.input)) + if kind != test.kind { + t.Errorf("test %d: kind mismatch: got %v, want %v", i, kind, test.kind) + } + if !bytes.Equal(val, unhex(test.val)) { + t.Errorf("test %d: val mismatch: got %x, want %s", i, val, test.val) + } + if !bytes.Equal(rest, unhex(test.rest)) { + t.Errorf("test %d: rest mismatch: got %x, want %s", i, rest, test.rest) + } + if err != test.err { + t.Errorf("test %d: error mismatch: got %q, want %q", i, err, test.err) + } + } +} + +func TestReadSize(t *testing.T) { + tests := []struct { + input string + slen byte + size uint64 + err error + }{ + {input: "", slen: 1, err: io.ErrUnexpectedEOF}, + {input: "FF", slen: 2, err: io.ErrUnexpectedEOF}, + {input: "00", slen: 1, err: ErrCanonSize}, + {input: "36", slen: 1, err: ErrCanonSize}, + {input: "37", slen: 1, err: ErrCanonSize}, + {input: "38", slen: 1, size: 0x38}, + {input: "FF", slen: 1, size: 0xFF}, + {input: "FFFF", slen: 2, size: 0xFFFF}, + {input: "FFFFFF", slen: 3, size: 0xFFFFFF}, + {input: "FFFFFFFF", slen: 4, size: 0xFFFFFFFF}, + {input: "FFFFFFFFFF", slen: 5, size: 0xFFFFFFFFFF}, + {input: "FFFFFFFFFFFF", slen: 6, size: 0xFFFFFFFFFFFF}, + {input: "FFFFFFFFFFFFFF", slen: 7, size: 0xFFFFFFFFFFFFFF}, + {input: "FFFFFFFFFFFFFFFF", slen: 8, size: 0xFFFFFFFFFFFFFFFF}, + {input: "0102", slen: 2, size: 0x0102}, + {input: "010203", slen: 3, size: 0x010203}, + {input: "01020304", slen: 4, size: 0x01020304}, + {input: "0102030405", slen: 5, size: 0x0102030405}, + {input: "010203040506", slen: 6, size: 0x010203040506}, + {input: "01020304050607", slen: 7, size: 0x01020304050607}, + {input: "0102030405060708", slen: 8, size: 0x0102030405060708}, + } + + for _, test := range tests { + size, err := readSize(unhex(test.input), test.slen) + if err != test.err { + t.Errorf("readSize(%s, %d): error mismatch: got %q, want %q", test.input, test.slen, err, test.err) + continue + } + if size != test.size { + t.Errorf("readSize(%s, %d): size mismatch: got %#x, want %#x", test.input, test.slen, size, test.size) + } + } +} diff --git a/bsc/rlp/typecache.go b/bsc/rlp/typecache.go new file mode 100644 index 0000000000..e9a1e3f9e2 --- /dev/null +++ b/bsc/rlp/typecache.go @@ -0,0 +1,215 @@ +// Copyright 2014 The go-ethereum Authors +// This file is part of the go-ethereum library. +// +// The go-ethereum library is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// The go-ethereum library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with the go-ethereum library. If not, see . + +package rlp + +import ( + "fmt" + "reflect" + "strings" + "sync" +) + +var ( + typeCacheMutex sync.RWMutex + typeCache = make(map[typekey]*typeinfo) +) + +type typeinfo struct { + decoder decoder + decoderErr error // error from makeDecoder + writer writer + writerErr error // error from makeWriter +} + +// tags represents struct tags. +type tags struct { + // rlp:"nil" controls whether empty input results in a nil pointer. + nilOK bool + + // This controls whether nil pointers are encoded/decoded as empty strings + // or empty lists. + nilKind Kind + + // rlp:"tail" controls whether this field swallows additional list + // elements. It can only be set for the last field, which must be + // of slice type. + tail bool + + // rlp:"-" ignores fields. + ignored bool +} + +// typekey is the key of a type in typeCache. It includes the struct tags because +// they might generate a different decoder. +type typekey struct { + reflect.Type + tags +} + +type decoder func(*Stream, reflect.Value) error + +type writer func(reflect.Value, *encbuf) error + +func cachedDecoder(typ reflect.Type) (decoder, error) { + info := cachedTypeInfo(typ, tags{}) + return info.decoder, info.decoderErr +} + +func cachedWriter(typ reflect.Type) (writer, error) { + info := cachedTypeInfo(typ, tags{}) + return info.writer, info.writerErr +} + +func cachedTypeInfo(typ reflect.Type, tags tags) *typeinfo { + typeCacheMutex.RLock() + info := typeCache[typekey{typ, tags}] + typeCacheMutex.RUnlock() + if info != nil { + return info + } + // not in the cache, need to generate info for this type. + typeCacheMutex.Lock() + defer typeCacheMutex.Unlock() + return cachedTypeInfo1(typ, tags) +} + +func cachedTypeInfo1(typ reflect.Type, tags tags) *typeinfo { + key := typekey{typ, tags} + info := typeCache[key] + if info != nil { + // another goroutine got the write lock first + return info + } + // put a dummy value into the cache before generating. + // if the generator tries to lookup itself, it will get + // the dummy value and won't call itself recursively. + info = new(typeinfo) + typeCache[key] = info + info.generate(typ, tags) + return info +} + +type field struct { + index int + info *typeinfo +} + +func structFields(typ reflect.Type) (fields []field, err error) { + lastPublic := lastPublicField(typ) + for i := 0; i < typ.NumField(); i++ { + if f := typ.Field(i); f.PkgPath == "" { // exported + tags, err := parseStructTag(typ, i, lastPublic) + if err != nil { + return nil, err + } + if tags.ignored { + continue + } + info := cachedTypeInfo1(f.Type, tags) + fields = append(fields, field{i, info}) + } + } + return fields, nil +} + +type structFieldError struct { + typ reflect.Type + field int + err error +} + +func (e structFieldError) Error() string { + return fmt.Sprintf("%v (struct field %v.%s)", e.err, e.typ, e.typ.Field(e.field).Name) +} + +type structTagError struct { + typ reflect.Type + field, tag, err string +} + +func (e structTagError) Error() string { + return fmt.Sprintf("rlp: invalid struct tag %q for %v.%s (%s)", e.tag, e.typ, e.field, e.err) +} + +func parseStructTag(typ reflect.Type, fi, lastPublic int) (tags, error) { + f := typ.Field(fi) + var ts tags + for _, t := range strings.Split(f.Tag.Get("rlp"), ",") { + switch t = strings.TrimSpace(t); t { + case "": + case "-": + ts.ignored = true + case "nil", "nilString", "nilList": + ts.nilOK = true + if f.Type.Kind() != reflect.Ptr { + return ts, structTagError{typ, f.Name, t, "field is not a pointer"} + } + switch t { + case "nil": + ts.nilKind = defaultNilKind(f.Type.Elem()) + case "nilString": + ts.nilKind = String + case "nilList": + ts.nilKind = List + } + case "tail": + ts.tail = true + if fi != lastPublic { + return ts, structTagError{typ, f.Name, t, "must be on last field"} + } + if f.Type.Kind() != reflect.Slice { + return ts, structTagError{typ, f.Name, t, "field type is not slice"} + } + default: + return ts, fmt.Errorf("rlp: unknown struct tag %q on %v.%s", t, typ, f.Name) + } + } + return ts, nil +} + +func lastPublicField(typ reflect.Type) int { + last := 0 + for i := 0; i < typ.NumField(); i++ { + if typ.Field(i).PkgPath == "" { + last = i + } + } + return last +} + +func (i *typeinfo) generate(typ reflect.Type, tags tags) { + i.decoder, i.decoderErr = makeDecoder(typ, tags) + i.writer, i.writerErr = makeWriter(typ, tags) +} + +// defaultNilKind determines whether a nil pointer to typ encodes/decodes +// as an empty string or empty list. +func defaultNilKind(typ reflect.Type) Kind { + k := typ.Kind() + if isUint(k) || k == reflect.String || k == reflect.Bool || isByteArray(typ) { + return String + } + return List +} + +func isUint(k reflect.Kind) bool { + return k >= reflect.Uint && k <= reflect.Uintptr +} + +func isByteArray(typ reflect.Type) bool { + return (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) && isByte(typ.Elem()) +} diff --git a/proto/cosmos/oracle/v1/event.proto b/proto/cosmos/oracle/v1/event.proto new file mode 100644 index 0000000000..080a17ba5c --- /dev/null +++ b/proto/cosmos/oracle/v1/event.proto @@ -0,0 +1,18 @@ +// Since: cosmos-sdk 0.43 +syntax = "proto3"; +package cosmos.oracle.v1; + +import "cosmos_proto/cosmos.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; + +message EventPackageClaim { + uint32 chain_id = 1; + uint32 channel_id = 2; + uint32 package_type = 3; + uint64 receive_sequence = 4; + int64 send_sequence = 5; + bool crash = 6; + string error_msg = 7; + int64 fee = 8; +} \ No newline at end of file diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto new file mode 100644 index 0000000000..f8406ceea8 --- /dev/null +++ b/proto/cosmos/oracle/v1/query.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package cosmos.crosschain.v1; + +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/crosschain/v1/crosschain.proto"; + +option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; + +// Query provides defines the gRPC querier service. +service Query { +} diff --git a/proto/cosmos/oracle/v1/tx.proto b/proto/cosmos/oracle/v1/tx.proto new file mode 100644 index 0000000000..4bd8dc3bd0 --- /dev/null +++ b/proto/cosmos/oracle/v1/tx.proto @@ -0,0 +1,32 @@ +syntax = "proto3"; +package cosmos.oracle.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; +option (gogoproto.equal_all) = true; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; +import "cosmos/msg/v1/msg.proto"; + +// Msg defines the oracle Msg service. +service Msg { + rpc Claim(MsgClaim) returns (MsgClaimResponse); +} + +// MsgClaim defines the Msg/Claim request type +message MsgClaim { + option (cosmos.msg.v1.signer) = "from_address"; + + option (gogoproto.equal) = false; + option (gogoproto.goproto_getters) = false; + + string from_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; + uint32 chain_id = 2; + uint64 sequence = 3; + bytes payload = 4; + repeated uint64 vote_address_set = 5; + bytes agg_signature = 6; +} + +// MsgClaimResponse defines the Msg/Claim response type +message MsgClaimResponse {} diff --git a/types/cross_chain.go b/types/cross_chain.go index 582071ef37..de26d50a90 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -7,7 +7,11 @@ import ( "math/big" "strconv" - "cosmossdk.io/errors" + "github.com/tendermint/tendermint/crypto" +) + +var ( + PegAccount = AccAddress(crypto.AddressHash([]byte("BFSPegAccount"))) // TODO: update if needed ) type CrossChainPackageType uint8 @@ -63,10 +67,21 @@ type CrossChainApplication interface { // TODO: define the execute result type ExecuteResult struct { - Err errors.Error + Err error Payload []byte } +func (c ExecuteResult) IsOk() bool { + return c.Err == nil +} + +func (c ExecuteResult) ErrMsg() string { + if c.Err == nil { + return "" + } + return c.Err.Error() +} + const ( CrossChainFeeLength = 32 PackageTypeLength = 1 diff --git a/types/tokens.go b/types/tokens.go new file mode 100644 index 0000000000..eea072c863 --- /dev/null +++ b/types/tokens.go @@ -0,0 +1,7 @@ +package types + +const ( + NativeTokenSymbol = "BNB" + + TokenMaxTotalSupply int64 = 9000000000000000000 // 90 billions with 8 decimal digits +) diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 4d840cf231..73788f0fde 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -208,3 +208,7 @@ func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramSpace.GetParamSet(ctx, ¶ms) return params } + +func (k Keeper) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication { + return k.cfg.channelIDToApp[channelID] +} diff --git a/x/crosschain/types/expected_keepers.go b/x/crosschain/types/expected_keepers.go deleted file mode 100644 index 804c94d571..0000000000 --- a/x/crosschain/types/expected_keepers.go +++ /dev/null @@ -1,10 +0,0 @@ -package types - -import sdk "github.com/cosmos/cosmos-sdk/types" - -type CrossChainKeeper interface { - GetSrcChainID() sdk.ChainID - IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) - GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission - GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 -} diff --git a/x/oracle/README.md b/x/oracle/README.md new file mode 100644 index 0000000000..63a8342e6c --- /dev/null +++ b/x/oracle/README.md @@ -0,0 +1,6 @@ + + +# Oracle + diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go new file mode 100644 index 0000000000..98701d3722 --- /dev/null +++ b/x/oracle/keeper/keeper.go @@ -0,0 +1,92 @@ +package keeper + +import ( + "fmt" + + sdkerrors "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/codec" + storetypes "github.com/cosmos/cosmos-sdk/store/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/metrics" + "github.com/cosmos/cosmos-sdk/x/oracle/types" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/prysmaticlabs/prysm/crypto/bls" + "github.com/willf/bitset" +) + +type Keeper struct { + cdc codec.BinaryCodec + storeKey storetypes.StoreKey + paramSpace paramtypes.Subspace + + StakingKeeper types.StakingKeeper + CrossChainKeeper types.CrossChainKeeper + BankKeeper types.BankKeeper + Metrics *metrics.Metrics + + feeCollectorName string // name of the FeeCollector ModuleAccount +} + +func NewKeeper( + cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace paramtypes.Subspace, feeCollector string, + crossChainKeeper types.CrossChainKeeper, bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, +) Keeper { + return Keeper{ + cdc: cdc, + storeKey: key, + paramSpace: paramSpace, + feeCollectorName: feeCollector, + + CrossChainKeeper: crossChainKeeper, + BankKeeper: bankKeeper, + StakingKeeper: stakingKeeper, + + Metrics: metrics.PrometheusMetrics(), + } +} + +// ProcessClaim checks the bls signature +func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { + validators := k.StakingKeeper.GetLastValidators(ctx) + validatorsBitSet := bitset.From(claim.VoteAddressSet) + if validatorsBitSet.Count() > uint(len(validators)) { + return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("number of validator set is larger than validators")) + } + + votedPubKeys := make([]bls.PublicKey, 0, validatorsBitSet.Count()) + for index, val := range validators { + if !validatorsBitSet.Test(uint(index)) { + continue + } + + // TODO: confirm the pub key + voteAddr, err := bls.PublicKeyFromBytes(val.ConsensusPubkey.Value) + if err != nil { + return sdkerrors.Wrapf(types.ErrBlsPubKey, fmt.Sprintf("BLS public key converts failed: %v", err)) + + } + votedPubKeys = append(votedPubKeys, voteAddr) + } + + // The valid voted validators should be no less than 2/3 validators. + if len(votedPubKeys) <= len(validators)*2/3 { + return sdkerrors.Wrapf(types.ErrBlsVotesNotEnough, fmt.Sprintf("not enough validators voted, need: %d, voted: %d", len(validators)*2/3, len(votedPubKeys))) + } + + // Verify the aggregated signature. + aggSig, err := bls.SignatureFromBytes(claim.AggSignature[:]) + if err != nil { + return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("BLS signature converts failed: %v", err)) + } + + if !aggSig.FastAggregateVerify(votedPubKeys, claim.GetBlsSignBytes()) { + return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("signature verify failed")) + } + + return nil +} + +// SendCoinsFromAccountToFeeCollector transfers amt to the fee collector account. +func (k Keeper) SendCoinsFromAccountToFeeCollector(ctx sdk.Context, senderAddr sdk.AccAddress, amt sdk.Coins) error { + return k.BankKeeper.SendCoinsFromAccountToModule(ctx, senderAddr, k.feeCollectorName, amt) +} diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go new file mode 100644 index 0000000000..77285f92af --- /dev/null +++ b/x/oracle/keeper/msg_server.go @@ -0,0 +1,183 @@ +package keeper + +import ( + "context" + "encoding/hex" + "fmt" + "runtime/debug" + + sdkerrors "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/bsc/rlp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/types" + "github.com/gogo/protobuf/proto" +) + +type msgServer struct { + oracleKeeper Keeper + stakingKeeper types.StakingKeeper +} + +// NewMsgServerImpl returns an implementation of the oracle MsgServer interface +// for the provided Keeper. +func NewMsgServerImpl(k Keeper, stakingKeeper types.StakingKeeper) types.MsgServer { + return &msgServer{ + oracleKeeper: k, + stakingKeeper: stakingKeeper, + } +} + +var _ types.MsgServer = msgServer{} + +func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.MsgClaimResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, sdk.ChainID(req.ChainId), types.RelayPackagesChannelId) + if sequence != req.Sequence { + return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", types.RelayPackagesChannelId, sequence)) + } + + err := k.oracleKeeper.ProcessClaim(ctx, req) + if err != nil { + return nil, err + } + + packages := types.Packages{} + err = rlp.DecodeBytes(req.Payload, &packages) + if err != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalidPayload, fmt.Sprintf("decode payload error")) + } + + events := make([]proto.Message, 0, len(packages)) + for _, pack := range packages { + event, err := handlePackage(ctx, k.oracleKeeper, sdk.ChainID(req.ChainId), &pack) + if err != nil { + // only do log, but let reset package get chance to execute. + ctx.Logger().With("module", "oracle").Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) + return nil, err + } + ctx.Logger().With("module", "oracle").Info(fmt.Sprintf("process package success, channel=%d, sequence=%d", pack.ChannelId, pack.Sequence)) + + events = append(events, event) + + // increase channel sequence + k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, sdk.ChainID(req.ChainId), pack.ChannelId) + } + + ctx.EventManager().EmitTypedEvents(events...) + + return &types.MsgClaimResponse{}, nil +} + +func handlePackage(ctx sdk.Context, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*types.EventPackageClaim, error) { + logger := ctx.Logger().With("module", "x/oracle") + + crossChainApp := oracleKeeper.CrossChainKeeper.GetCrossChainApp(pack.ChannelId) + if crossChainApp == nil { + return nil, sdkerrors.Wrapf(types.ErrChannelNotRegistered, "channel %d not registered", pack.ChannelId) + } + + sequence := oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, chainId, pack.ChannelId) + if sequence != pack.Sequence { + return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) + } + + packageType, _, relayFee, err := sdk.DecodePackageHeader(pack.Payload) + if err != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "payload header is invalid") + } + + if !sdk.IsValidCrossChainPackageType(packageType) { + return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("pcakge type %d is invalid", packageType)) + } + + feeAmount := relayFee.Int64() + if feeAmount < 0 { + return nil, sdkerrors.Wrapf(types.ErrFeeOverflow, fmt.Sprintf("fee(%s) is overflow", relayFee.String())) + } + + fee := sdk.Coins{sdk.Coin{Denom: sdk.NativeTokenSymbol, Amount: sdk.NewInt(feeAmount)}} + err = oracleKeeper.SendCoinsFromAccountToFeeCollector(ctx, sdk.PegAccount, fee) + if err != nil { + return nil, err + } + + cacheCtx, write := ctx.CacheContext() + crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageType, feeAmount) + if result.IsOk() { + write() + } else { + oracleKeeper.Metrics.ErrNumOfChannels.With("channel_id", fmt.Sprintf("%d", pack.ChannelId)).Add(1) + } + + // write ack package + var sendSequence int64 = -1 + if packageType == sdk.SynCrossChainPackageType { + if crash { + var ibcErr error + var sendSeq uint64 + if len(pack.Payload) >= sdk.PackageHeaderLength { + sendSeq, ibcErr = oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, + pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.PackageHeaderLength:]) + } else { + logger.Error("found payload without header", "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) + return nil, sdkerrors.Wrapf(types.ErrInvalidPackage, fmt.Sprintf("payload without header")) + } + + if ibcErr != nil { + logger.Error("failed to write FailAckCrossChainPackage", "err", err) + return nil, ibcErr + } + sendSequence = int64(sendSeq) + } else { + if len(result.Payload) != 0 { + sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, + pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload) + if err != nil { + logger.Error("failed to write AckCrossChainPackage", "err", err) + return nil, err + } + sendSequence = int64(sendSeq) + } + } + } + + claimEvent := &types.EventPackageClaim{ + ChainId: uint32(chainId), + ChannelId: uint32(pack.ChannelId), + PackageType: uint32(packageType), + ReceiveSequence: pack.Sequence, + SendSequence: sendSequence, + Fee: feeAmount, + Crash: crash, + ErrorMsg: result.ErrMsg(), + } + + return claimEvent, nil +} + +func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, packageType sdk.CrossChainPackageType, relayerFee int64) (crash bool, result sdk.ExecuteResult) { + defer func() { + if r := recover(); r != nil { + log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack())) + logger := ctx.Logger().With("module", "oracle") + logger.Error("execute claim panic", "err_log", log) + crash = true + result = sdk.ExecuteResult{ + Err: fmt.Errorf("execute claim failed: %v", r), + } + } + }() + + switch packageType { + case sdk.SynCrossChainPackageType: + result = app.ExecuteSynPackage(ctx, payload[sdk.PackageHeaderLength:], relayerFee) + case sdk.AckCrossChainPackageType: + result = app.ExecuteAckPackage(ctx, payload[sdk.PackageHeaderLength:]) + case sdk.FailAckCrossChainPackageType: + result = app.ExecuteFailAckPackage(ctx, payload[sdk.PackageHeaderLength:]) + default: + panic(fmt.Sprintf("receive unexpected package type %d", packageType)) + } + return +} diff --git a/x/oracle/keeper/querier.go b/x/oracle/keeper/querier.go new file mode 100644 index 0000000000..6708edf7c7 --- /dev/null +++ b/x/oracle/keeper/querier.go @@ -0,0 +1,18 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + abci "github.com/tendermint/tendermint/abci/types" +) + +func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { + switch path[0] { + + default: + return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) + } + } +} diff --git a/x/oracle/metrics/metrics.go b/x/oracle/metrics/metrics.go new file mode 100644 index 0000000000..f0f649ab8d --- /dev/null +++ b/x/oracle/metrics/metrics.go @@ -0,0 +1,31 @@ +package metrics + +import ( + metricsPkg "github.com/go-kit/kit/metrics" + "github.com/go-kit/kit/metrics/discard" + "github.com/go-kit/kit/metrics/prometheus" + stdprometheus "github.com/prometheus/client_golang/prometheus" +) + +// Metrics contains Metrics exposed by this package. +type Metrics struct { + ErrNumOfChannels metricsPkg.Counter +} + +// PrometheusMetrics returns Metrics build using Prometheus client library. +func PrometheusMetrics() *Metrics { + return &Metrics{ + ErrNumOfChannels: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ + Subsystem: "oracle", + Name: "err_num_of_channels", + Help: "The error numbers of channel happened from boot", + }, []string{"channel_id"}), + } +} + +// NopMetrics returns no-op Metrics. +func NopMetrics() *Metrics { + return &Metrics{ + ErrNumOfChannels: discard.NewCounter(), + } +} diff --git a/x/oracle/module.go b/x/oracle/module.go new file mode 100644 index 0000000000..99be572dad --- /dev/null +++ b/x/oracle/module.go @@ -0,0 +1,132 @@ +package crosschain + +import ( + "encoding/json" + "math/rand" + + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/x/oracle/keeper" + "github.com/cosmos/cosmos-sdk/x/oracle/types" + "github.com/cosmos/cosmos-sdk/x/params/client/cli" +) + +var ( + _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleSimulation = AppModule{} +) + +// AppModuleBasic defines the basic application module used by the params module. +type AppModuleBasic struct{} + +// Name returns the params module's name. +func (AppModuleBasic) Name() string { + return types.ModuleName +} + +// RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} + +// DefaultGenesis returns default genesis state as raw bytes for the params +// module. +func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return nil } + +// ValidateGenesis performs genesis state validation for the params module. +func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { + return nil +} + +// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. +func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { + +} + +// GetTxCmd returns no root tx command for the params module. +func (AppModuleBasic) GetTxCmd() *cobra.Command { return nil } + +// GetQueryCmd returns no root query command for the params module. +func (AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.NewQueryCmd() +} + +func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {} + +// AppModule implements an application module for the distribution module. +type AppModule struct { + AppModuleBasic + + keeper keeper.Keeper +} + +// NewAppModule creates a new AppModule object +func NewAppModule(k keeper.Keeper) AppModule { + return AppModule{ + AppModuleBasic: AppModuleBasic{}, + keeper: k, + } +} + +func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} + +// InitGenesis performs a no-op. +func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { + return []abci.ValidatorUpdate{} +} + +// Deprecated: Route returns the message routing key for the params module. +func (AppModule) Route() sdk.Route { + return sdk.Route{} +} + +// GenerateGenesisState performs a no-op. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) {} + +// QuerierRoute returns the x/param module's querier route name. +func (AppModule) QuerierRoute() string { return types.QuerierRoute } + +// LegacyQuerierHandler returns the x/params querier handler. +func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { + return keeper.NewQuerier(am.keeper, legacyQuerierCdc) +} + +// RegisterServices registers a gRPC query service to respond to the +// module-specific gRPC queries. +func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterQueryServer(cfg.QueryServer(), am.keeper) +} + +// ProposalContents returns all the params content functions used to +// simulate governance proposals. +func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// RandomizedParams creates randomized distribution param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { + return nil +} + +// RegisterStoreDecoder doesn't register any type. +func (AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) {} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(_ module.SimulationState) []simtypes.WeightedOperation { + return nil +} + +// ExportGenesis performs a no-op. +func (am AppModule) ExportGenesis(_ sdk.Context, _ codec.JSONCodec) json.RawMessage { + return nil +} + +// ConsensusVersion implements AppModule/ConsensusVersion. +func (AppModule) ConsensusVersion() uint64 { return 1 } diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go new file mode 100644 index 0000000000..956b536831 --- /dev/null +++ b/x/oracle/types/codec.go @@ -0,0 +1,8 @@ +package types + +import "github.com/cosmos/cosmos-sdk/codec" + +var ( + amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewAminoCodec(amino) +) diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go new file mode 100644 index 0000000000..2be1b8623b --- /dev/null +++ b/x/oracle/types/errors.go @@ -0,0 +1,17 @@ +package types + +import sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + +var ( + ErrChannelNotRegistered = sdkerrors.Register(ModuleName, 1, "channel is not registered") + ErrInvalidReceiveSequence = sdkerrors.Register(ModuleName, 2, "receive sequence is invalid") + ErrInvalidPayloadHeader = sdkerrors.Register(ModuleName, 3, "payload header is invalid") + ErrInvalidPackageType = sdkerrors.Register(ModuleName, 4, "package type is invalid") + ErrFeeOverflow = sdkerrors.Register(ModuleName, 5, "fee is overflow") + ErrInvalidPackage = sdkerrors.Register(ModuleName, 6, "package is invalid") + ErrInvalidPayload = sdkerrors.Register(ModuleName, 7, "payload is invalid") + ErrValidatorSet = sdkerrors.Register(ModuleName, 8, "validator set is invalid") + ErrBlsPubKey = sdkerrors.Register(ModuleName, 9, "public key is invalid") + ErrBlsVotesNotEnough = sdkerrors.Register(ModuleName, 10, "bls votes is not enough") + ErrInvalidBlsSignature = sdkerrors.Register(ModuleName, 11, "bls signature is invalid") +) diff --git a/x/oracle/types/event.pb.go b/x/oracle/types/event.pb.go new file mode 100644 index 0000000000..0efefc03d6 --- /dev/null +++ b/x/oracle/types/event.pb.go @@ -0,0 +1,577 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/oracle/v1/event.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + 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 EventPackageClaim struct { + ChainId uint32 `protobuf:"varint,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + ChannelId uint32 `protobuf:"varint,2,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + PackageType uint32 `protobuf:"varint,3,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` + ReceiveSequence uint64 `protobuf:"varint,4,opt,name=receive_sequence,json=receiveSequence,proto3" json:"receive_sequence,omitempty"` + SendSequence int64 `protobuf:"varint,5,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` + Crash bool `protobuf:"varint,6,opt,name=crash,proto3" json:"crash,omitempty"` + ErrorMsg string `protobuf:"bytes,7,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` + Fee int64 `protobuf:"varint,8,opt,name=fee,proto3" json:"fee,omitempty"` +} + +func (m *EventPackageClaim) Reset() { *m = EventPackageClaim{} } +func (m *EventPackageClaim) String() string { return proto.CompactTextString(m) } +func (*EventPackageClaim) ProtoMessage() {} +func (*EventPackageClaim) Descriptor() ([]byte, []int) { + return fileDescriptor_3e254cedc4112fb0, []int{0} +} +func (m *EventPackageClaim) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *EventPackageClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_EventPackageClaim.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 *EventPackageClaim) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventPackageClaim.Merge(m, src) +} +func (m *EventPackageClaim) XXX_Size() int { + return m.Size() +} +func (m *EventPackageClaim) XXX_DiscardUnknown() { + xxx_messageInfo_EventPackageClaim.DiscardUnknown(m) +} + +var xxx_messageInfo_EventPackageClaim proto.InternalMessageInfo + +func (m *EventPackageClaim) GetChainId() uint32 { + if m != nil { + return m.ChainId + } + return 0 +} + +func (m *EventPackageClaim) GetChannelId() uint32 { + if m != nil { + return m.ChannelId + } + return 0 +} + +func (m *EventPackageClaim) GetPackageType() uint32 { + if m != nil { + return m.PackageType + } + return 0 +} + +func (m *EventPackageClaim) GetReceiveSequence() uint64 { + if m != nil { + return m.ReceiveSequence + } + return 0 +} + +func (m *EventPackageClaim) GetSendSequence() int64 { + if m != nil { + return m.SendSequence + } + return 0 +} + +func (m *EventPackageClaim) GetCrash() bool { + if m != nil { + return m.Crash + } + return false +} + +func (m *EventPackageClaim) GetErrorMsg() string { + if m != nil { + return m.ErrorMsg + } + return "" +} + +func (m *EventPackageClaim) GetFee() int64 { + if m != nil { + return m.Fee + } + return 0 +} + +func init() { + proto.RegisterType((*EventPackageClaim)(nil), "cosmos.oracle.v1.EventPackageClaim") +} + +func init() { proto.RegisterFile("cosmos/oracle/v1/event.proto", fileDescriptor_3e254cedc4112fb0) } + +var fileDescriptor_3e254cedc4112fb0 = []byte{ + // 321 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xbb, 0x4e, 0xc3, 0x30, + 0x14, 0x86, 0xeb, 0x5e, 0x53, 0xd3, 0x8a, 0x62, 0x31, 0xa4, 0x5c, 0xa2, 0x00, 0x4b, 0x10, 0x22, + 0x51, 0xc5, 0x1b, 0x80, 0x3a, 0x74, 0x40, 0x42, 0x81, 0x89, 0x25, 0x72, 0x9d, 0x43, 0x12, 0xb5, + 0x89, 0x83, 0x9d, 0x46, 0xf4, 0x01, 0xd8, 0x79, 0x2c, 0xc6, 0x8e, 0x8c, 0xa8, 0x7d, 0x11, 0x14, + 0xc7, 0xc0, 0x94, 0xfc, 0xdf, 0xf7, 0xfb, 0x48, 0x3e, 0xc6, 0x27, 0x8c, 0xcb, 0x94, 0x4b, 0x8f, + 0x0b, 0xca, 0x96, 0xe0, 0x95, 0x13, 0x0f, 0x4a, 0xc8, 0x0a, 0x37, 0x17, 0xbc, 0xe0, 0x64, 0x54, + 0x5b, 0xb7, 0xb6, 0x6e, 0x39, 0x39, 0x1a, 0xd7, 0x24, 0x50, 0xde, 0xd3, 0x5a, 0x85, 0xf3, 0xf7, + 0x26, 0x3e, 0x98, 0x56, 0x87, 0x1f, 0x28, 0x5b, 0xd0, 0x08, 0xee, 0x96, 0x34, 0x49, 0xc9, 0x18, + 0x1b, 0x2c, 0xa6, 0x49, 0x16, 0x24, 0xa1, 0x89, 0x6c, 0xe4, 0x0c, 0xfd, 0x9e, 0xca, 0xb3, 0x90, + 0x9c, 0x62, 0xcc, 0x62, 0x9a, 0x65, 0xb0, 0xac, 0x64, 0x53, 0xc9, 0xbe, 0x26, 0xb3, 0x90, 0x9c, + 0xe1, 0x41, 0x5e, 0x4f, 0x0a, 0x8a, 0x75, 0x0e, 0x66, 0x4b, 0x15, 0xf6, 0x34, 0x7b, 0x5a, 0xe7, + 0x40, 0x2e, 0xf1, 0x48, 0x00, 0x83, 0xa4, 0x84, 0x40, 0xc2, 0xeb, 0x0a, 0x32, 0x06, 0x66, 0xdb, + 0x46, 0x4e, 0xdb, 0xdf, 0xd7, 0xfc, 0x51, 0x63, 0x72, 0x81, 0x87, 0x12, 0xb2, 0xf0, 0xbf, 0xd7, + 0xb1, 0x91, 0xd3, 0xf2, 0x07, 0x15, 0xfc, 0x2b, 0x1d, 0xe2, 0x0e, 0x13, 0x54, 0xc6, 0x66, 0xd7, + 0x46, 0x8e, 0xe1, 0xd7, 0x81, 0x1c, 0xe3, 0x3e, 0x08, 0xc1, 0x45, 0x90, 0xca, 0xc8, 0xec, 0xd9, + 0xc8, 0xe9, 0xfb, 0x86, 0x02, 0xf7, 0x32, 0x22, 0x23, 0xdc, 0x7a, 0x01, 0x30, 0x0d, 0x35, 0xad, + 0xfa, 0xbd, 0x9d, 0x7e, 0x6e, 0x2d, 0xb4, 0xd9, 0x5a, 0xe8, 0x7b, 0x6b, 0xa1, 0x8f, 0x9d, 0xd5, + 0xd8, 0xec, 0xac, 0xc6, 0xd7, 0xce, 0x6a, 0x3c, 0x5f, 0x45, 0x49, 0x11, 0xaf, 0xe6, 0x2e, 0xe3, + 0xa9, 0x5e, 0x9d, 0xfe, 0x5c, 0xcb, 0x70, 0xe1, 0xbd, 0xfd, 0x3e, 0x42, 0x75, 0x5b, 0x39, 0xef, + 0xaa, 0xad, 0xde, 0xfc, 0x04, 0x00, 0x00, 0xff, 0xff, 0x51, 0xea, 0x27, 0x3a, 0xa2, 0x01, 0x00, + 0x00, +} + +func (m *EventPackageClaim) 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 *EventPackageClaim) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Fee != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.Fee)) + i-- + dAtA[i] = 0x40 + } + if len(m.ErrorMsg) > 0 { + i -= len(m.ErrorMsg) + copy(dAtA[i:], m.ErrorMsg) + i = encodeVarintEvent(dAtA, i, uint64(len(m.ErrorMsg))) + i-- + dAtA[i] = 0x3a + } + if m.Crash { + i-- + if m.Crash { + dAtA[i] = 1 + } else { + dAtA[i] = 0 + } + i-- + dAtA[i] = 0x30 + } + if m.SendSequence != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.SendSequence)) + i-- + dAtA[i] = 0x28 + } + if m.ReceiveSequence != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.ReceiveSequence)) + i-- + dAtA[i] = 0x20 + } + if m.PackageType != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.PackageType)) + i-- + dAtA[i] = 0x18 + } + if m.ChannelId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.ChannelId)) + i-- + dAtA[i] = 0x10 + } + if m.ChainId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.ChainId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintEvent(dAtA []byte, offset int, v uint64) int { + offset -= sovEvent(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *EventPackageClaim) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChainId != 0 { + n += 1 + sovEvent(uint64(m.ChainId)) + } + if m.ChannelId != 0 { + n += 1 + sovEvent(uint64(m.ChannelId)) + } + if m.PackageType != 0 { + n += 1 + sovEvent(uint64(m.PackageType)) + } + if m.ReceiveSequence != 0 { + n += 1 + sovEvent(uint64(m.ReceiveSequence)) + } + if m.SendSequence != 0 { + n += 1 + sovEvent(uint64(m.SendSequence)) + } + if m.Crash { + n += 2 + } + l = len(m.ErrorMsg) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) + } + if m.Fee != 0 { + n += 1 + sovEvent(uint64(m.Fee)) + } + return n +} + +func sovEvent(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozEvent(x uint64) (n int) { + return sovEvent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *EventPackageClaim) 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 ErrIntOverflowEvent + } + 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: EventPackageClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: EventPackageClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + m.ChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) + } + m.ChannelId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field PackageType", wireType) + } + m.PackageType = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.PackageType |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ReceiveSequence", wireType) + } + m.ReceiveSequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ReceiveSequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field SendSequence", wireType) + } + m.SendSequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.SendSequence |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Crash", wireType) + } + var v int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.Crash = bool(v != 0) + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ErrorMsg", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + 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 ErrInvalidLengthEvent + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ErrorMsg = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 8: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + } + m.Fee = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Fee |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipEvent(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthEvent + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipEvent(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, ErrIntOverflowEvent + } + 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, ErrIntOverflowEvent + } + 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, ErrIntOverflowEvent + } + 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, ErrInvalidLengthEvent + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupEvent + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthEvent + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthEvent = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowEvent = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupEvent = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go new file mode 100644 index 0000000000..73d08c1199 --- /dev/null +++ b/x/oracle/types/expected_keepers.go @@ -0,0 +1,22 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +type StakingKeeper interface { + GetLastValidators(ctx sdk.Context) (validators []types.Validator) +} + +type CrossChainKeeper interface { + CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, + packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) + GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication + GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 + IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) +} + +type BankKeeper interface { + SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error +} diff --git a/x/oracle/types/keys.go b/x/oracle/types/keys.go new file mode 100644 index 0000000000..a7ab172ef2 --- /dev/null +++ b/x/oracle/types/keys.go @@ -0,0 +1,12 @@ +package types + +import sdk "github.com/cosmos/cosmos-sdk/types" + +const ( + ModuleName = "oracle" + QuerierRoute = ModuleName + + // RelayPackagesChannelId is not a communication channel actually, we just use it to record sequence. + RelayPackagesChannelName = "relayPackages" + RelayPackagesChannelId sdk.ChannelID = 0x00 +) diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go new file mode 100644 index 0000000000..312c01cda1 --- /dev/null +++ b/x/oracle/types/msgs.go @@ -0,0 +1,96 @@ +package types + +import ( + "fmt" + "math" + + "github.com/cosmos/cosmos-sdk/bsc/rlp" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/prysmaticlabs/prysm/crypto/hash" +) + +const ( + ValidatorBitSetLength = 4 + BLSPublicKeyLength = 48 + BLSSignatureLength = 96 +) + +type BLSPublicKey [BLSPublicKeyLength]byte +type BLSSignature [BLSSignatureLength]byte + +// Route implements the LegacyMsg interface. +func (m MsgClaim) Route() string { return sdk.MsgTypeURL(&m) } + +// Type implements the LegacyMsg interface. +func (m MsgClaim) Type() string { return sdk.MsgTypeURL(&m) } + +// GetSignBytes implements the LegacyMsg interface. +func (m MsgClaim) GetSignBytes() []byte { + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&m)) +} + +// ValidateBasic does a sanity check on the provided data. +func (m *MsgClaim) ValidateBasic() error { + if _, err := sdk.AccAddressFromBech32(m.FromAddress); err != nil { + return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) + } + + if m.ChainId > math.MaxUint16 { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, + fmt.Sprintf("chain id should not be larger than %d", math.MaxUint16)) + } + + if len(m.VoteAddressSet) != ValidatorBitSetLength { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, + fmt.Sprintf("length of vote addresse set should be %d", ValidatorBitSetLength)) + } + + if len(m.AggSignature) != BLSSignatureLength { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, + fmt.Sprintf("length of vote addresse set should be %d", BLSSignatureLength), + ) + } + + return nil +} + +// GetSigners returns the expected signers for MsgCancelUpgrade. +func (m *MsgClaim) GetSigners() []sdk.AccAddress { + fromAddress, _ := sdk.AccAddressFromBech32(m.FromAddress) + return []sdk.AccAddress{fromAddress} +} + +// GetBlsSignBytes returns the sign bytes of bls signature +func (m *MsgClaim) GetBlsSignBytes() [32]byte { + blsClaim := &BlsClaim{ + ChainId: m.ChainId, + Sequence: m.Sequence, + Payload: m.Payload, + } + return blsClaim.GetSignBytes() +} + +type BlsClaim struct { + ChainId uint32 + Sequence uint64 + Payload []byte +} + +func (c *BlsClaim) GetSignBytes() [32]byte { + bts, err := rlp.EncodeToBytes(c) + if err != nil { + panic("encode bls claim error") + } + + btsHash := hash.Hash(bts) + return btsHash +} + +type Packages []Package + +type Package struct { + ChannelId sdk.ChannelID + Sequence uint64 + Payload []byte +} diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go new file mode 100644 index 0000000000..43cdeb8910 --- /dev/null +++ b/x/oracle/types/msgs_test.go @@ -0,0 +1,21 @@ +package types + +import ( + "encoding/hex" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestBlsClaim(t *testing.T) { + claim := &BlsClaim{ + ChainId: 1, + Sequence: 1, + Payload: []byte("test payload"), + } + + signBytes := claim.GetSignBytes() + + require.Equal(t, "3b0858e23a9ca1335fff8539c8a27037ed29a4e5c2258a92c590ca9ad319abe0", + hex.EncodeToString(signBytes[:])) +} diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go new file mode 100644 index 0000000000..98679cfd06 --- /dev/null +++ b/x/oracle/types/query.pb.go @@ -0,0 +1,87 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/oracle/v1/query.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-sdk/x/crosschain/types" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + math "math" +) + +// 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 + +func init() { proto.RegisterFile("cosmos/oracle/v1/query.proto", fileDescriptor_9f804c4644f3aaef) } + +var fileDescriptor_9f804c4644f3aaef = []byte{ + // 192 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, + 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xc8, 0xea, 0x25, 0x17, 0xe5, + 0x17, 0x17, 0x27, 0x67, 0x24, 0x66, 0xe6, 0xe9, 0x95, 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, + 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x32, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, + 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x89, 0x25, 0x99, 0xf9, 0x79, 0xc5, 0x50, + 0x59, 0x55, 0xa8, 0x3d, 0x08, 0x93, 0x40, 0x76, 0x21, 0x99, 0x0b, 0x56, 0x66, 0xc4, 0xce, 0xc5, + 0x1a, 0x08, 0xb2, 0xdf, 0xc9, 0xf5, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, + 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, + 0xb4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x61, 0x86, 0x82, 0x29, + 0xdd, 0xe2, 0x94, 0x6c, 0xfd, 0x0a, 0x98, 0x4f, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, + 0xc6, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x37, 0xc8, 0x15, 0xcf, 0xe7, 0x00, 0x00, 0x00, +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +// QueryServer is the server API for Query service. +type QueryServer interface { +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.crosschain.v1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{}, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/oracle/v1/query.proto", +} diff --git a/x/oracle/types/tx.pb.go b/x/oracle/types/tx.pb.go new file mode 100644 index 0000000000..d3d6e9c498 --- /dev/null +++ b/x/oracle/types/tx.pb.go @@ -0,0 +1,803 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/oracle/v1/tx.proto + +package types + +import ( + context "context" + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/cosmos/cosmos-sdk/types/msgservice" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// MsgClaim defines the Msg/Claim request type +type MsgClaim struct { + FromAddress string `protobuf:"bytes,1,opt,name=from_address,json=fromAddress,proto3" json:"from_address,omitempty"` + ChainId uint32 `protobuf:"varint,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` + Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` + Payload []byte `protobuf:"bytes,4,opt,name=payload,proto3" json:"payload,omitempty"` + VoteAddressSet []uint64 `protobuf:"varint,5,rep,packed,name=vote_address_set,json=voteAddressSet,proto3" json:"vote_address_set,omitempty"` + AggSignature []byte `protobuf:"bytes,6,opt,name=agg_signature,json=aggSignature,proto3" json:"agg_signature,omitempty"` +} + +func (m *MsgClaim) Reset() { *m = MsgClaim{} } +func (m *MsgClaim) String() string { return proto.CompactTextString(m) } +func (*MsgClaim) ProtoMessage() {} +func (*MsgClaim) Descriptor() ([]byte, []int) { + return fileDescriptor_836933fb4b988e66, []int{0} +} +func (m *MsgClaim) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgClaim) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgClaim.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 *MsgClaim) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgClaim.Merge(m, src) +} +func (m *MsgClaim) XXX_Size() int { + return m.Size() +} +func (m *MsgClaim) XXX_DiscardUnknown() { + xxx_messageInfo_MsgClaim.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgClaim proto.InternalMessageInfo + +// MsgClaimResponse defines the Msg/Claim response type +type MsgClaimResponse struct { +} + +func (m *MsgClaimResponse) Reset() { *m = MsgClaimResponse{} } +func (m *MsgClaimResponse) String() string { return proto.CompactTextString(m) } +func (*MsgClaimResponse) ProtoMessage() {} +func (*MsgClaimResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_836933fb4b988e66, []int{1} +} +func (m *MsgClaimResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgClaimResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgClaimResponse.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 *MsgClaimResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgClaimResponse.Merge(m, src) +} +func (m *MsgClaimResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgClaimResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgClaimResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgClaimResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgClaim)(nil), "cosmos.oracle.v1.MsgClaim") + proto.RegisterType((*MsgClaimResponse)(nil), "cosmos.oracle.v1.MsgClaimResponse") +} + +func init() { proto.RegisterFile("cosmos/oracle/v1/tx.proto", fileDescriptor_836933fb4b988e66) } + +var fileDescriptor_836933fb4b988e66 = []byte{ + // 392 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xbf, 0xee, 0xd3, 0x30, + 0x10, 0xc7, 0xe3, 0xfe, 0xc7, 0xb4, 0xa8, 0xb2, 0x2a, 0xe1, 0x66, 0x48, 0xa3, 0xb2, 0x44, 0xa0, + 0x26, 0x2a, 0x6c, 0x30, 0x51, 0x06, 0xd4, 0xa1, 0x0c, 0xe9, 0xc6, 0x12, 0xb9, 0x89, 0x71, 0x23, + 0x9a, 0x38, 0xc4, 0x6e, 0xd5, 0xae, 0x9d, 0x18, 0x79, 0x84, 0x8e, 0x8c, 0x0c, 0x3c, 0x04, 0x63, + 0xc5, 0xc4, 0x88, 0xd2, 0x01, 0x1e, 0x03, 0x25, 0x8e, 0x91, 0x40, 0xfa, 0x4d, 0xf6, 0xdd, 0xe7, + 0xee, 0xab, 0xf3, 0x7d, 0x0d, 0xc7, 0x21, 0x17, 0x09, 0x17, 0x1e, 0xcf, 0x49, 0xb8, 0xa3, 0xde, + 0x61, 0xee, 0xc9, 0xa3, 0x9b, 0xe5, 0x5c, 0x72, 0x34, 0x54, 0xc8, 0x55, 0xc8, 0x3d, 0xcc, 0xcd, + 0x11, 0xe3, 0x8c, 0x57, 0xd0, 0x2b, 0x6f, 0xaa, 0xce, 0xac, 0x25, 0x02, 0x05, 0xea, 0x26, 0x85, + 0x1e, 0xd6, 0xea, 0x89, 0x60, 0xa5, 0x74, 0x22, 0x98, 0x02, 0xd3, 0x73, 0x03, 0xf6, 0x56, 0x82, + 0xbd, 0xda, 0x91, 0x38, 0x41, 0x2f, 0x60, 0xff, 0x5d, 0xce, 0x93, 0x80, 0x44, 0x51, 0x4e, 0x85, + 0xc0, 0xc0, 0x06, 0xce, 0xbd, 0x05, 0xfe, 0xfe, 0x75, 0x36, 0xaa, 0xd5, 0x5e, 0x2a, 0xb2, 0x96, + 0x79, 0x9c, 0x32, 0xff, 0x7e, 0x59, 0x5d, 0xa7, 0xd0, 0x18, 0xf6, 0xc2, 0x2d, 0x89, 0xd3, 0x20, + 0x8e, 0x70, 0xc3, 0x06, 0xce, 0xc0, 0xef, 0x56, 0xf1, 0x32, 0x42, 0x26, 0xec, 0x09, 0xfa, 0x61, + 0x4f, 0xd3, 0x90, 0xe2, 0xa6, 0x0d, 0x9c, 0x96, 0xff, 0x37, 0x46, 0x18, 0x76, 0x33, 0x72, 0xda, + 0x71, 0x12, 0xe1, 0x96, 0x0d, 0x9c, 0xbe, 0xaf, 0x43, 0xe4, 0xc0, 0xe1, 0x81, 0x4b, 0xaa, 0xa7, + 0x09, 0x04, 0x95, 0xb8, 0x6d, 0x37, 0x9d, 0x96, 0xff, 0xa0, 0xcc, 0xeb, 0x51, 0xa8, 0x44, 0x8f, + 0xe0, 0x80, 0x30, 0x16, 0x88, 0x98, 0xa5, 0x44, 0xee, 0x73, 0x8a, 0x3b, 0x95, 0x52, 0x9f, 0x30, + 0xb6, 0xd6, 0xb9, 0xe7, 0xe3, 0x8f, 0x97, 0x89, 0xf1, 0xfb, 0x32, 0x31, 0xce, 0xbf, 0xbe, 0x3c, + 0xfe, 0xe7, 0x9d, 0x53, 0x04, 0x87, 0x7a, 0x07, 0x3e, 0x15, 0x19, 0x4f, 0x05, 0x7d, 0xfa, 0x06, + 0x36, 0x57, 0x82, 0xa1, 0xd7, 0xb0, 0xad, 0x76, 0x63, 0xba, 0xff, 0xbb, 0xe0, 0xea, 0x1e, 0x73, + 0x7a, 0x37, 0xd3, 0x7a, 0x8b, 0xe5, 0xe7, 0xc2, 0x02, 0xdf, 0x0a, 0x0b, 0x5c, 0x0b, 0x0b, 0xfc, + 0x2c, 0x2c, 0xf0, 0xe9, 0x66, 0x19, 0xd7, 0x9b, 0x65, 0xfc, 0xb8, 0x59, 0xc6, 0xdb, 0x27, 0x2c, + 0x96, 0xdb, 0xfd, 0xc6, 0x0d, 0x79, 0x52, 0x1b, 0x57, 0x1f, 0x33, 0x11, 0xbd, 0xf7, 0x8e, 0xfa, + 0x57, 0xc8, 0x53, 0x46, 0xc5, 0xa6, 0x53, 0x59, 0xf7, 0xec, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, + 0xc1, 0x94, 0xe4, 0x54, 0x33, 0x02, 0x00, 0x00, +} + +func (this *MsgClaimResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MsgClaimResponse) + if !ok { + that2, ok := that.(MsgClaimResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + return true +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// MsgClient is the client API for Msg service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type MsgClient interface { + Claim(ctx context.Context, in *MsgClaim, opts ...grpc.CallOption) (*MsgClaimResponse, error) +} + +type msgClient struct { + cc grpc1.ClientConn +} + +func NewMsgClient(cc grpc1.ClientConn) MsgClient { + return &msgClient{cc} +} + +func (c *msgClient) Claim(ctx context.Context, in *MsgClaim, opts ...grpc.CallOption) (*MsgClaimResponse, error) { + out := new(MsgClaimResponse) + err := c.cc.Invoke(ctx, "/cosmos.oracle.v1.Msg/Claim", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// MsgServer is the server API for Msg service. +type MsgServer interface { + Claim(context.Context, *MsgClaim) (*MsgClaimResponse, error) +} + +// UnimplementedMsgServer can be embedded to have forward compatible implementations. +type UnimplementedMsgServer struct { +} + +func (*UnimplementedMsgServer) Claim(ctx context.Context, req *MsgClaim) (*MsgClaimResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Claim not implemented") +} + +func RegisterMsgServer(s grpc1.Server, srv MsgServer) { + s.RegisterService(&_Msg_serviceDesc, srv) +} + +func _Msg_Claim_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgClaim) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).Claim(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.oracle.v1.Msg/Claim", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).Claim(ctx, req.(*MsgClaim)) + } + return interceptor(ctx, in, info, handler) +} + +var _Msg_serviceDesc = grpc.ServiceDesc{ + ServiceName: "cosmos.oracle.v1.Msg", + HandlerType: (*MsgServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Claim", + Handler: _Msg_Claim_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/oracle/v1/tx.proto", +} + +func (m *MsgClaim) 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 *MsgClaim) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.AggSignature) > 0 { + i -= len(m.AggSignature) + copy(dAtA[i:], m.AggSignature) + i = encodeVarintTx(dAtA, i, uint64(len(m.AggSignature))) + i-- + dAtA[i] = 0x32 + } + if len(m.VoteAddressSet) > 0 { + dAtA2 := make([]byte, len(m.VoteAddressSet)*10) + var j1 int + for _, num := range m.VoteAddressSet { + 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 = encodeVarintTx(dAtA, i, uint64(j1)) + i-- + dAtA[i] = 0x2a + } + if len(m.Payload) > 0 { + i -= len(m.Payload) + copy(dAtA[i:], m.Payload) + i = encodeVarintTx(dAtA, i, uint64(len(m.Payload))) + i-- + dAtA[i] = 0x22 + } + if m.Sequence != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.Sequence)) + i-- + dAtA[i] = 0x18 + } + if m.ChainId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.ChainId)) + i-- + dAtA[i] = 0x10 + } + if len(m.FromAddress) > 0 { + i -= len(m.FromAddress) + copy(dAtA[i:], m.FromAddress) + i = encodeVarintTx(dAtA, i, uint64(len(m.FromAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgClaimResponse) 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 *MsgClaimResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgClaimResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func encodeVarintTx(dAtA []byte, offset int, v uint64) int { + offset -= sovTx(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgClaim) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.FromAddress) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if m.ChainId != 0 { + n += 1 + sovTx(uint64(m.ChainId)) + } + if m.Sequence != 0 { + n += 1 + sovTx(uint64(m.Sequence)) + } + l = len(m.Payload) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.VoteAddressSet) > 0 { + l = 0 + for _, e := range m.VoteAddressSet { + l += sovTx(uint64(e)) + } + n += 1 + sovTx(uint64(l)) + l + } + l = len(m.AggSignature) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + return n +} + +func (m *MsgClaimResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func sovTx(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTx(x uint64) (n int) { + return sovTx(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgClaim) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgClaim: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgClaim: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FromAddress", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.FromAddress = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + } + m.ChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Payload = append(m.Payload[:0], dAtA[iNdEx:postIndex]...) + if m.Payload == nil { + m.Payload = []byte{} + } + iNdEx = postIndex + case 5: + if wireType == 0 { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.VoteAddressSet = append(m.VoteAddressSet, v) + } else if wireType == 2 { + var packedLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + packedLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if packedLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + packedLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + var elementCount int + var count int + for _, integer := range dAtA[iNdEx:postIndex] { + if integer < 128 { + count++ + } + } + elementCount = count + if elementCount != 0 && len(m.VoteAddressSet) == 0 { + m.VoteAddressSet = make([]uint64, 0, elementCount) + } + for iNdEx < postIndex { + var v uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + v |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + m.VoteAddressSet = append(m.VoteAddressSet, v) + } + } else { + return fmt.Errorf("proto: wrong wireType = %d for field VoteAddressSet", wireType) + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AggSignature", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AggSignature = append(m.AggSignature[:0], dAtA[iNdEx:postIndex]...) + if m.AggSignature == nil { + m.AggSignature = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgClaimResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgClaimResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgClaimResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTx(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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrIntOverflowTx + } + 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, ErrInvalidLengthTx + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTx + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTx + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTx = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTx = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTx = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/oracle/types/types.go b/x/oracle/types/types.go new file mode 100644 index 0000000000..ab1254f4c2 --- /dev/null +++ b/x/oracle/types/types.go @@ -0,0 +1 @@ +package types From 52049e5c51a00ba735930e3d1e9ddd1698d0a320 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 23 Nov 2022 16:23:20 +0800 Subject: [PATCH 06/50] add unit tests for cross chain module --- simapp/app.go | 8 +- x/crosschain/keeper/keeper.go | 54 ++++++++++--- x/crosschain/keeper/keeper_test.go | 117 +++++++++++++++++++++++++++++ x/crosschain/testutil/mockapp.go | 75 ++++++++++++++++++ x/crosschain/types/keys.go | 8 -- x/crosschain/types/params.go | 2 +- x/oracle/keeper/keeper.go | 2 +- 7 files changed, 243 insertions(+), 23 deletions(-) create mode 100644 x/crosschain/keeper/keeper_test.go create mode 100644 x/crosschain/testutil/mockapp.go diff --git a/simapp/app.go b/simapp/app.go index c959729744..a6410e1b53 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -54,6 +54,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/crisis" crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + crosschainkeeper "github.com/cosmos/cosmos-sdk/x/crosschain/keeper" + crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" @@ -184,6 +186,7 @@ type SimApp struct { GroupKeeper groupkeeper.Keeper NFTKeeper nftkeeper.Keeper GashubKeeper gashubkeeper.Keeper + CrossChainKeeper crosschainkeeper.Keeper // the module manager mm *module.Manager @@ -224,7 +227,7 @@ func NewSimApp( minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, evidencetypes.StoreKey, capabilitytypes.StoreKey, - authzkeeper.StoreKey, nftkeeper.StoreKey, group.StoreKey, gashubtypes.StoreKey, + authzkeeper.StoreKey, nftkeeper.StoreKey, group.StoreKey, gashubtypes.StoreKey,crosschaintypes.StoreKey ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) // NOTE: The testingkey is just mounted for testing purposes. Actual applications should @@ -327,6 +330,8 @@ func NewSimApp( app.NFTKeeper = nftkeeper.NewKeeper(keys[nftkeeper.StoreKey], appCodec, app.AccountKeeper, app.BankKeeper) + app.CrossChainKeeper = crosschainkeeper.NewKeeper(appCodec, keys[crosschaintypes.StoreKey], app.GetSubspace(crosschaintypes.ModuleName)) + // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( appCodec, keys[evidencetypes.StoreKey], &app.StakingKeeper, app.SlashingKeeper, @@ -702,6 +707,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govv1.ParamKeyTable()) paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(gashubtypes.ModuleName) + paramsKeeper.Subspace(crosschaintypes.ModuleName) return paramsKeeper } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 73788f0fde..978f2858bd 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -15,7 +15,7 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -// Keeper of the ibc store +// Keeper of the cross chain store type Keeper struct { cdc codec.BinaryCodec @@ -28,28 +28,38 @@ type Keeper struct { func NewKeeper( cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace paramtypes.Subspace, ) Keeper { + // set KeyTable if it has not already been set + if !paramSpace.HasKeyTable() { + paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) + } + return Keeper{ cdc: cdc, storeKey: key, + cfg: newCrossChainCfg(), paramSpace: paramSpace, } } +// Logger inits the logger for cross chain module func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } +// GetRelayerFeeParam returns the default relayer fee for cross chain tx func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { - var relayerFeeParam int64 + var relayerFeeParam uint64 k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) - relayerFee = bsc.ConvertBCAmountToBSCAmount(relayerFeeParam) + relayerFee = bsc.ConvertBCAmountToBSCAmount(int64(relayerFeeParam)) return } +// SetParams sets the params of cross chain module func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) } +// CreateRawIBCPackage creates a cross chain package with default cross chain fee func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) { @@ -61,15 +71,7 @@ func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, ch return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) } -func (k Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission { - kvStore := ctx.KVStore(k.storeKey) - bz := kvStore.Get(types.BuildChannelPermissionKey(destChainID, channelID)) - if bz == nil { - return sdk.ChannelForbidden - } - return sdk.ChannelPermission(bz[0]) -} - +// CreateRawIBCPackageWithFee creates a cross chain package with given cross chain fee func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int) (uint64, error) { @@ -108,6 +110,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai return sequence, nil } +// RegisterChannel register a channel to the cross chain module with the cross chain app func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChainApplication) error { _, ok := k.cfg.nameToChannelID[name] if ok { @@ -117,12 +120,16 @@ func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChai if ok { return fmt.Errorf("duplicated channel id") } + if app == nil { + return fmt.Errorf("nil cross chain app") + } k.cfg.nameToChannelID[name] = id k.cfg.channelIDToName[id] = name k.cfg.channelIDToApp[id] = app return nil } +// RegisterDestChain registers a chain with name func (k Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { _, ok := k.cfg.destChainNameToID[name] if ok { @@ -137,19 +144,33 @@ func (k Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { return nil } +// SetChannelSendPermission sets the channel send permission func (k Keeper) SetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, permission sdk.ChannelPermission) { kvStore := ctx.KVStore(k.storeKey) kvStore.Set(types.BuildChannelPermissionKey(destChainID, channelID), []byte{byte(permission)}) } +// GetChannelSendPermission gets the channel send permission by channel id +func (k Keeper) GetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) sdk.ChannelPermission { + kvStore := ctx.KVStore(k.storeKey) + bz := kvStore.Get(types.BuildChannelPermissionKey(destChainID, channelID)) + if bz == nil { + return sdk.ChannelForbidden + } + return sdk.ChannelPermission(bz[0]) +} + +// SetSrcChainID sets the current chain id func (k Keeper) SetSrcChainID(srcChainID sdk.ChainID) { k.cfg.srcChainID = srcChainID } +// GetSrcChainID gets the current chain id func (k Keeper) GetSrcChainID() sdk.ChainID { return k.cfg.srcChainID } +// GetDestChainID returns the chain id by name func (k Keeper) GetDestChainID(name string) (sdk.ChainID, error) { destChainID, exist := k.cfg.destChainNameToID[name] if !exist { @@ -158,28 +179,34 @@ func (k Keeper) GetDestChainID(name string) (sdk.ChainID, error) { return destChainID, nil } +// GetIBCPackage returns the ibc package by sequence func (k Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { kvStore := ctx.KVStore(k.storeKey) key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelId, sequence) return kvStore.Get(key), nil } +// GetSendSequence returns the sending sequence of the channel func (k Keeper) GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { return k.getSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) } +// IncrSendSequence increases the sending sequence of the channel func (k Keeper) IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { k.incrSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) } +// GetReceiveSequence returns the receiving sequence of the channel func (k Keeper) GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { return k.getSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) } +// IncrReceiveSequence increases the receiving sequence of the channel func (k Keeper) IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { k.incrSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) } +// getSequence returns the sequence with a prefix func (k Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) uint64 { kvStore := ctx.KVStore(k.storeKey) bz := kvStore.Get(types.BuildChannelSequenceKey(destChainID, channelID, prefix)) @@ -189,6 +216,7 @@ func (k Keeper) getSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID return binary.BigEndian.Uint64(bz) } +// incrSequence increases the sequence with a prefix func (k Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, prefix []byte) { var sequence uint64 kvStore := ctx.KVStore(k.storeKey) @@ -204,11 +232,13 @@ func (k Keeper) incrSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID kvStore.Set(types.BuildChannelSequenceKey(destChainID, channelID, prefix), sequenceBytes) } +// GetParams returns the current params func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { k.paramSpace.GetParamSet(ctx, ¶ms) return params } +// GetCrossChainApp returns the cross chain app by channel id func (k Keeper) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication { return k.cfg.channelIDToApp[channelID] } diff --git a/x/crosschain/keeper/keeper_test.go b/x/crosschain/keeper/keeper_test.go new file mode 100644 index 0000000000..e73f64b10f --- /dev/null +++ b/x/crosschain/keeper/keeper_test.go @@ -0,0 +1,117 @@ +package keeper_test + +import ( + "testing" + + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/crosschain/testutil" + "github.com/cosmos/cosmos-sdk/x/crosschain/types" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtime "github.com/tendermint/tendermint/types/time" +) + +type TestSuite struct { + suite.Suite + + app *simapp.SimApp + ctx sdk.Context +} + +func (s *TestSuite) SetupTest() { + app := simapp.Setup(s.T(), false) + ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + ctx = ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()}) + + app.CrossChainKeeper.SetParams(ctx, types.DefaultParams()) + + s.app = app + s.ctx = ctx +} + +func TestTestSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) +} + +func (s *TestSuite) TestIncrSendSequence() { + beforeSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + s.app.CrossChainKeeper.IncrSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + afterSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + s.Require().EqualValues(afterSequence, beforeSequence+1) +} + +func (s *TestSuite) TestIncrReceiveSequence() { + beforeSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + s.app.CrossChainKeeper.IncrReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + afterSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + + s.Require().EqualValues(afterSequence, beforeSequence+1) +} + +func (s *TestSuite) TestRegisterDestChain() { + testName := "test" + testChainId := sdk.ChainID(100) + + err := s.app.CrossChainKeeper.RegisterDestChain(testName, testChainId) + + s.Require().NoError(err) + + chainId, err := s.app.CrossChainKeeper.GetDestChainID(testName) + s.Require().NoError(err) + + s.Require().EqualValues(chainId, testChainId) + + // check duplicate name + err = s.app.CrossChainKeeper.RegisterDestChain(testName, testChainId) + s.Require().ErrorContains(err, "duplicated destination chain name") + + // check duplicate channel id + err = s.app.CrossChainKeeper.RegisterDestChain("another chain", testChainId) + s.Require().ErrorContains(err, "duplicated destination chain chainID") +} + +func (s *TestSuite) TestRegisterChannel() { + testChannelName := "test channel" + testChannelId := sdk.ChannelID(100) + + err := s.app.CrossChainKeeper.RegisterChannel(testChannelName, testChannelId, &testutil.MockCrossChainApplication{}) + + s.Require().NoError(err) + + app := s.app.CrossChainKeeper.GetCrossChainApp(testChannelId) + s.Require().NotNil(app) + + // check duplicate name + err = s.app.CrossChainKeeper.RegisterChannel(testChannelName, testChannelId, app) + s.Require().ErrorContains(err, "duplicated channel name") + + // check duplicate channel id + err = s.app.CrossChainKeeper.RegisterChannel("another channel", testChannelId, app) + s.Require().ErrorContains(err, "duplicated channel id") + + // check nil app + err = s.app.CrossChainKeeper.RegisterChannel("another channel", sdk.ChannelID(101), nil) + s.Require().ErrorContains(err, "nil cross chain app") +} + +func (s *TestSuite) TestCreateIBCPackage() { + sequence, err := s.app.CrossChainKeeper.CreateRawIBCPackage(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sdk.CrossChainPackageType(1), []byte("test payload")) + s.Require().NoError(err) + s.Require().EqualValues(0, sequence) + + _, err = s.app.CrossChainKeeper.GetIBCPackage(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sequence) + s.Require().NoError(err) +} + +func (s *TestSuite) TestSetChannelSendPermission() { + s.app.CrossChainKeeper.SetChannelSendPermission(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sdk.ChannelAllow) + + permission := s.app.CrossChainKeeper.GetChannelSendPermission(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + s.Require().EqualValues(sdk.ChannelAllow, permission) +} diff --git a/x/crosschain/testutil/mockapp.go b/x/crosschain/testutil/mockapp.go new file mode 100644 index 0000000000..8ed4f3f396 --- /dev/null +++ b/x/crosschain/testutil/mockapp.go @@ -0,0 +1,75 @@ +// Code generated by MockGen. DO NOT EDIT. + +package testutil + +import ( + reflect "reflect" + + types "github.com/cosmos/cosmos-sdk/types" + gomock "github.com/golang/mock/gomock" +) + +// MockCrossChainApplication is a mock of CrossChainApplication interface +type MockCrossChainApplication struct { + ctrl *gomock.Controller + recorder *MockCrossChainApplicationMockRecorder +} + +// MockCrossChainApplicationMockRecorder is the mock recorder for MockCrossChainApplication +type MockCrossChainApplicationMockRecorder struct { + mock *MockCrossChainApplication +} + +// NewMockCrossChainApplication creates a new mock instance +func NewMockCrossChainApplication(ctrl *gomock.Controller) *MockCrossChainApplication { + mock := &MockCrossChainApplication{ctrl: ctrl} + mock.recorder = &MockCrossChainApplicationMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use +func (m *MockCrossChainApplication) EXPECT() *MockCrossChainApplicationMockRecorder { + return m.recorder +} + +// ExecuteSynPackage mocks base method +func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, payload []byte, relayerFee int64) types.ExecuteResult { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExecuteSynPackage", ctx, payload, relayerFee) + ret0, _ := ret[0].(types.ExecuteResult) + return ret0 +} + +// ExecuteSynPackage indicates an expected call of ExecuteSynPackage +func (mr *MockCrossChainApplicationMockRecorder) ExecuteSynPackage(ctx, payload, relayerFee interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteSynPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteSynPackage), ctx, payload, relayerFee) +} + +// ExecuteAckPackage mocks base method +func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, payload []byte) types.ExecuteResult { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExecuteAckPackage", ctx, payload) + ret0, _ := ret[0].(types.ExecuteResult) + return ret0 +} + +// ExecuteAckPackage indicates an expected call of ExecuteAckPackage +func (mr *MockCrossChainApplicationMockRecorder) ExecuteAckPackage(ctx, payload interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteAckPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteAckPackage), ctx, payload) +} + +// ExecuteFailAckPackage mocks base method +func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, payload []byte) types.ExecuteResult { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ExecuteFailAckPackage", ctx, payload) + ret0, _ := ret[0].(types.ExecuteResult) + return ret0 +} + +// ExecuteFailAckPackage indicates an expected call of ExecuteFailAckPackage +func (mr *MockCrossChainApplicationMockRecorder) ExecuteFailAckPackage(ctx, payload interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteFailAckPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteFailAckPackage), ctx, payload) +} diff --git a/x/crosschain/types/keys.go b/x/crosschain/types/keys.go index 0b40defaa6..d84f7e7326 100644 --- a/x/crosschain/types/keys.go +++ b/x/crosschain/types/keys.go @@ -85,11 +85,3 @@ func BuildChannelPermissionKey(destChainID sdk.ChainID, channelID sdk.ChannelID) copy(key[prefixLength+destChainIDLength:], []byte{byte(channelID)}) return key } - -func BuildChannelPermissionsPrefixKey(destChainID sdk.ChainID) []byte { - key := make([]byte, prefixLength+destChainIDLength) - - copy(key[:prefixLength], PrefixForChannelPermissionKey) - binary.BigEndian.PutUint16(key[prefixLength:prefixLength+destChainIDLength], uint16(destChainID)) - return key -} diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 02ea050035..62fb9903ff 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -11,7 +11,7 @@ const ( ) var ( - KeyParamRelayerFee = []byte("relayerFee") + KeyParamRelayerFee = []byte("RelayerFee") ) func DefaultParams() Params { diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 98701d3722..5653a8aed6 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -74,7 +74,7 @@ func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { } // Verify the aggregated signature. - aggSig, err := bls.SignatureFromBytes(claim.AggSignature[:]) + aggSig, err := bls.SignatureFromBytes(claim.AggSignature) if err != nil { return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("BLS signature converts failed: %v", err)) } From b20761271cda00ccd7b1aca1180f31d638b3e1a0 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 23 Nov 2022 19:48:39 +0800 Subject: [PATCH 07/50] add tests for oracle msgs --- x/oracle/types/msgs.go | 6 ++- x/oracle/types/msgs_test.go | 100 ++++++++++++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 312c01cda1..c631fd1281 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -41,6 +41,10 @@ func (m *MsgClaim) ValidateBasic() error { fmt.Sprintf("chain id should not be larger than %d", math.MaxUint16)) } + if len(m.Payload) == 0 { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("payload should not be empty")) + } + if len(m.VoteAddressSet) != ValidatorBitSetLength { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("length of vote addresse set should be %d", ValidatorBitSetLength)) @@ -48,7 +52,7 @@ func (m *MsgClaim) ValidateBasic() error { if len(m.AggSignature) != BLSSignatureLength { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("length of vote addresse set should be %d", BLSSignatureLength), + fmt.Sprintf("length of signature should be %d", BLSSignatureLength), ) } diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index 43cdeb8910..e85028c305 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -1,9 +1,15 @@ package types import ( + "bytes" "encoding/hex" + "fmt" + "math" "testing" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/simapp" + "github.com/cosmos/cosmos-sdk/testutil" "github.com/stretchr/testify/require" ) @@ -19,3 +25,97 @@ func TestBlsClaim(t *testing.T) { require.Equal(t, "3b0858e23a9ca1335fff8539c8a27037ed29a4e5c2258a92c590ca9ad319abe0", hex.EncodeToString(signBytes[:])) } + +func TestValidateBasic(t *testing.T) { + cdc := simapp.MakeTestEncodingConfig().Codec + addr, _, err := testutil.GenerateCoinKey(hd.Secp256k1, cdc) + require.NoError(t, err) + + tests := []struct { + claimMsg MsgClaim + expectedPass bool + errorMsg string + }{ + { + MsgClaim{ + FromAddress: "random string", + ChainId: 1, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{1, 2}, + AggSignature: []byte("test sig"), + }, + false, + "invalid from address", + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: math.MaxUint16 + 1, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{1, 2}, + AggSignature: []byte("test sig"), + }, + false, + "chain id should not be larger than", + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: 100, + Sequence: 1, + Payload: []byte{}, + VoteAddressSet: []uint64{1, 2}, + AggSignature: []byte("test sig"), + }, + false, + "payload should not be empty", + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: 100, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{1, 2}, + AggSignature: []byte("test sig"), + }, + false, + fmt.Sprintf("length of vote addresse set should be %d", ValidatorBitSetLength), + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: 100, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{1, 2, 3, 4}, + AggSignature: []byte("test sig"), + }, + false, + fmt.Sprintf("length of signature should be %d", BLSSignatureLength), + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: 100, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{1, 2, 3, 4}, + AggSignature: bytes.Repeat([]byte{0}, BLSSignatureLength), + }, + true, + "", + }, + } + + for i, test := range tests { + if test.expectedPass { + require.Nil(t, test.claimMsg.ValidateBasic(), "test: %v", i) + } else { + err := test.claimMsg.ValidateBasic() + require.ErrorContains(t, err, test.errorMsg) + } + } +} From 6c033517beaca24e5840c6e9617b5e31a1ad9063 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Thu, 24 Nov 2022 17:11:27 +0800 Subject: [PATCH 08/50] check is relayer in turn --- proto/cosmos/oracle/v1/oracle.proto | 12 ++ proto/cosmos/oracle/v1/query.proto | 2 +- proto/cosmos/oracle/v1/tx.proto | 7 +- simapp/app.go | 9 +- x/oracle/keeper/keeper.go | 51 +++++ x/oracle/keeper/msg_server.go | 12 +- x/oracle/types/errors.go | 2 + x/oracle/types/keys.go | 1 + x/oracle/types/msgs.go | 22 +- x/oracle/types/msgs_test.go | 35 +++- x/oracle/types/oracle.pb.go | 303 ++++++++++++++++++++++++++++ x/oracle/types/params.go | 45 +++++ x/oracle/types/tx.pb.go | 165 ++++++++------- 13 files changed, 554 insertions(+), 112 deletions(-) create mode 100644 proto/cosmos/oracle/v1/oracle.proto create mode 100644 x/oracle/types/oracle.pb.go create mode 100644 x/oracle/types/params.go diff --git a/proto/cosmos/oracle/v1/oracle.proto b/proto/cosmos/oracle/v1/oracle.proto new file mode 100644 index 0000000000..c401a0ad6b --- /dev/null +++ b/proto/cosmos/oracle/v1/oracle.proto @@ -0,0 +1,12 @@ +syntax = "proto3"; +package cosmos.oracle.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; + +import "gogoproto/gogo.proto"; +import "cosmos_proto/cosmos.proto"; + +// Params holds parameters for the oracle module. +message Params { + uint64 relayer_timeout = 1; +} diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto index f8406ceea8..d89610138b 100644 --- a/proto/cosmos/oracle/v1/query.proto +++ b/proto/cosmos/oracle/v1/query.proto @@ -3,7 +3,7 @@ package cosmos.crosschain.v1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; -import "cosmos/crosschain/v1/crosschain.proto"; +import "cosmos/crosschain/v1/oracle.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; diff --git a/proto/cosmos/oracle/v1/tx.proto b/proto/cosmos/oracle/v1/tx.proto index 4bd8dc3bd0..e4f9da65ea 100644 --- a/proto/cosmos/oracle/v1/tx.proto +++ b/proto/cosmos/oracle/v1/tx.proto @@ -23,9 +23,10 @@ message MsgClaim { string from_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; uint32 chain_id = 2; uint64 sequence = 3; - bytes payload = 4; - repeated uint64 vote_address_set = 5; - bytes agg_signature = 6; + uint64 timestamp = 4; + bytes payload = 5; + repeated fixed64 vote_address_set = 6; + bytes agg_signature = 7; } // MsgClaimResponse defines the Msg/Claim response type diff --git a/simapp/app.go b/simapp/app.go index a6410e1b53..661dcfe03e 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -86,6 +86,8 @@ import ( "github.com/cosmos/cosmos-sdk/x/nft" nftkeeper "github.com/cosmos/cosmos-sdk/x/nft/keeper" nftmodule "github.com/cosmos/cosmos-sdk/x/nft/module" + oraclekeeper "github.com/cosmos/cosmos-sdk/x/oracle/keeper" + oracletypes "github.com/cosmos/cosmos-sdk/x/oracle/types" "github.com/cosmos/cosmos-sdk/x/params" paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" @@ -187,6 +189,7 @@ type SimApp struct { NFTKeeper nftkeeper.Keeper GashubKeeper gashubkeeper.Keeper CrossChainKeeper crosschainkeeper.Keeper + OracleKeeper oraclekeeper.Keeper // the module manager mm *module.Manager @@ -227,7 +230,8 @@ func NewSimApp( minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, govtypes.StoreKey, paramstypes.StoreKey, upgradetypes.StoreKey, feegrant.StoreKey, evidencetypes.StoreKey, capabilitytypes.StoreKey, - authzkeeper.StoreKey, nftkeeper.StoreKey, group.StoreKey, gashubtypes.StoreKey,crosschaintypes.StoreKey + authzkeeper.StoreKey, nftkeeper.StoreKey, group.StoreKey, gashubtypes.StoreKey, crosschaintypes.StoreKey, + oracletypes.ModuleName, ) tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) // NOTE: The testingkey is just mounted for testing purposes. Actual applications should @@ -331,6 +335,8 @@ func NewSimApp( app.NFTKeeper = nftkeeper.NewKeeper(keys[nftkeeper.StoreKey], appCodec, app.AccountKeeper, app.BankKeeper) app.CrossChainKeeper = crosschainkeeper.NewKeeper(appCodec, keys[crosschaintypes.StoreKey], app.GetSubspace(crosschaintypes.ModuleName)) + app.OracleKeeper = oraclekeeper.NewKeeper(appCodec, keys[oracletypes.StoreKey], app.GetSubspace(oracletypes.ModuleName), authtypes.FeeCollectorName, + app.CrossChainKeeper, app.BankKeeper, app.StakingKeeper) // create evidence keeper with router evidenceKeeper := evidencekeeper.NewKeeper( @@ -708,6 +714,7 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(crisistypes.ModuleName) paramsKeeper.Subspace(gashubtypes.ModuleName) paramsKeeper.Subspace(crosschaintypes.ModuleName) + paramsKeeper.Subspace(oracletypes.ModuleName) return paramsKeeper } diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 5653a8aed6..39a85ef433 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -10,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/oracle/metrics" "github.com/cosmos/cosmos-sdk/x/oracle/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/willf/bitset" ) @@ -31,6 +32,11 @@ func NewKeeper( cdc codec.BinaryCodec, key storetypes.StoreKey, paramSpace paramtypes.Subspace, feeCollector string, crossChainKeeper types.CrossChainKeeper, bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper, ) Keeper { + // set KeyTable if it has not already been set + if !paramSpace.HasKeyTable() { + paramSpace = paramSpace.WithKeyTable(types.ParamKeyTable()) + } + return Keeper{ cdc: cdc, storeKey: key, @@ -45,9 +51,54 @@ func NewKeeper( } } +// GetRelayerTimeoutParam returns the default relayer timeout for oracle claim +func (k Keeper) GetRelayerTimeoutParam(ctx sdk.Context) uint64 { + var relayerTimeoutParam uint64 + k.paramSpace.Get(ctx, types.KeyParamRelayerTimeout, &relayerTimeoutParam) + return relayerTimeoutParam +} + +func (k Keeper) isValidatorInTurn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { + var validatorIndex int64 = -1 + for index, validator := range validators { + consAddr, err := validator.GetConsAddr() + if err != nil { + return false, err + } + if consAddr.String() == claim.FromAddress { + validatorIndex = int64(index) + break + } + } + + if validatorIndex < 0 { + return false, sdkerrors.Wrapf(types.ErrNotValidator, fmt.Sprintf("sender is not validator")) + } + + curTime := ctx.BlockTime().Unix() + relayerTimeout := k.GetRelayerTimeoutParam(ctx) + // check block time with package timestamp + if uint64(curTime)-claim.Timestamp > relayerTimeout { + return true, nil + } + + // check inturn validator index + inturnValidatorIndex := claim.Timestamp % uint64(len(validators)) + return uint64(validatorIndex) == inturnValidatorIndex, nil +} + // ProcessClaim checks the bls signature func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { validators := k.StakingKeeper.GetLastValidators(ctx) + + inturn, err := k.isValidatorInTurn(ctx, validators, claim) + if err != nil { + return err + } + if !inturn { + return sdkerrors.Wrapf(types.ErrValidatorNotInTurn, fmt.Sprintf("validator is not in turn")) + } + validatorsBitSet := bitset.From(claim.VoteAddressSet) if validatorsBitSet.Count() > uint(len(validators)) { return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("number of validator set is larger than validators")) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 77285f92af..d68cd78851 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -50,7 +50,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg events := make([]proto.Message, 0, len(packages)) for _, pack := range packages { - event, err := handlePackage(ctx, k.oracleKeeper, sdk.ChainID(req.ChainId), &pack) + event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.ChainId), &pack) if err != nil { // only do log, but let reset package get chance to execute. ctx.Logger().With("module", "oracle").Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) @@ -69,7 +69,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg return &types.MsgClaimResponse{}, nil } -func handlePackage(ctx sdk.Context, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*types.EventPackageClaim, error) { +func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*types.EventPackageClaim, error) { logger := ctx.Logger().With("module", "x/oracle") crossChainApp := oracleKeeper.CrossChainKeeper.GetCrossChainApp(pack.ChannelId) @@ -82,13 +82,17 @@ func handlePackage(ctx sdk.Context, oracleKeeper Keeper, chainId sdk.ChainID, pa return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) } - packageType, _, relayFee, err := sdk.DecodePackageHeader(pack.Payload) + packageType, timestamp, relayFee, err := sdk.DecodePackageHeader(pack.Payload) if err != nil { return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "payload header is invalid") } + if timestamp != req.Timestamp { + return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp is not the same in payload header") + } + if !sdk.IsValidCrossChainPackageType(packageType) { - return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("pcakge type %d is invalid", packageType)) + return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageType)) } feeAmount := relayFee.Int64() diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index 2be1b8623b..552c0ba0fa 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -14,4 +14,6 @@ var ( ErrBlsPubKey = sdkerrors.Register(ModuleName, 9, "public key is invalid") ErrBlsVotesNotEnough = sdkerrors.Register(ModuleName, 10, "bls votes is not enough") ErrInvalidBlsSignature = sdkerrors.Register(ModuleName, 11, "bls signature is invalid") + ErrNotValidator = sdkerrors.Register(ModuleName, 12, "sender is not validator") + ErrValidatorNotInTurn = sdkerrors.Register(ModuleName, 13, "validator is not in turn") ) diff --git a/x/oracle/types/keys.go b/x/oracle/types/keys.go index a7ab172ef2..0311fe1d05 100644 --- a/x/oracle/types/keys.go +++ b/x/oracle/types/keys.go @@ -4,6 +4,7 @@ import sdk "github.com/cosmos/cosmos-sdk/types" const ( ModuleName = "oracle" + StoreKey = ModuleName QuerierRoute = ModuleName // RelayPackagesChannelId is not a communication channel actually, we just use it to record sequence. diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index c631fd1281..9d21026cdd 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -11,7 +11,7 @@ import ( ) const ( - ValidatorBitSetLength = 4 + ValidatorBitSetLength = 4 // 256 bits BLSPublicKeyLength = 48 BLSSignatureLength = 96 ) @@ -56,6 +56,12 @@ func (m *MsgClaim) ValidateBasic() error { ) } + if m.Timestamp == 0 { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, + fmt.Sprintf("timestamp should not be 0"), + ) + } + return nil } @@ -68,17 +74,19 @@ func (m *MsgClaim) GetSigners() []sdk.AccAddress { // GetBlsSignBytes returns the sign bytes of bls signature func (m *MsgClaim) GetBlsSignBytes() [32]byte { blsClaim := &BlsClaim{ - ChainId: m.ChainId, - Sequence: m.Sequence, - Payload: m.Payload, + ChainId: m.ChainId, + Timestamp: m.Timestamp, + Sequence: m.Sequence, + Payload: m.Payload, } return blsClaim.GetSignBytes() } type BlsClaim struct { - ChainId uint32 - Sequence uint64 - Payload []byte + ChainId uint32 + Timestamp uint64 + Sequence uint64 + Payload []byte } func (c *BlsClaim) GetSignBytes() [32]byte { diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index e85028c305..eb4fc03e22 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -6,6 +6,7 @@ import ( "fmt" "math" "testing" + "time" "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/simapp" @@ -15,14 +16,15 @@ import ( func TestBlsClaim(t *testing.T) { claim := &BlsClaim{ - ChainId: 1, - Sequence: 1, - Payload: []byte("test payload"), + ChainId: 1, + Sequence: 1, + Timestamp: 1000, + Payload: []byte("test payload"), } signBytes := claim.GetSignBytes() - require.Equal(t, "3b0858e23a9ca1335fff8539c8a27037ed29a4e5c2258a92c590ca9ad319abe0", + require.Equal(t, "954d4fe4c768c275f14ef32929ab83e182a4de3c0aef38964efdf0bc8f76eaff", hex.EncodeToString(signBytes[:])) } @@ -42,7 +44,7 @@ func TestValidateBasic(t *testing.T) { ChainId: 1, Sequence: 1, Payload: []byte("test payload"), - VoteAddressSet: []uint64{1, 2}, + VoteAddressSet: []uint64{0, 1}, AggSignature: []byte("test sig"), }, false, @@ -54,7 +56,7 @@ func TestValidateBasic(t *testing.T) { ChainId: math.MaxUint16 + 1, Sequence: 1, Payload: []byte("test payload"), - VoteAddressSet: []uint64{1, 2}, + VoteAddressSet: []uint64{0, 1}, AggSignature: []byte("test sig"), }, false, @@ -66,7 +68,7 @@ func TestValidateBasic(t *testing.T) { ChainId: 100, Sequence: 1, Payload: []byte{}, - VoteAddressSet: []uint64{1, 2}, + VoteAddressSet: []uint64{0, 1}, AggSignature: []byte("test sig"), }, false, @@ -78,7 +80,7 @@ func TestValidateBasic(t *testing.T) { ChainId: 100, Sequence: 1, Payload: []byte("test payload"), - VoteAddressSet: []uint64{1, 2}, + VoteAddressSet: []uint64{0, 1}, AggSignature: []byte("test sig"), }, false, @@ -90,7 +92,7 @@ func TestValidateBasic(t *testing.T) { ChainId: 100, Sequence: 1, Payload: []byte("test payload"), - VoteAddressSet: []uint64{1, 2, 3, 4}, + VoteAddressSet: []uint64{0, 1, 2, 3}, AggSignature: []byte("test sig"), }, false, @@ -102,9 +104,22 @@ func TestValidateBasic(t *testing.T) { ChainId: 100, Sequence: 1, Payload: []byte("test payload"), - VoteAddressSet: []uint64{1, 2, 3, 4}, + VoteAddressSet: []uint64{0, 1, 2, 3}, AggSignature: bytes.Repeat([]byte{0}, BLSSignatureLength), }, + false, + "timestamp should not be 0", + }, + { + MsgClaim{ + FromAddress: addr.String(), + ChainId: 100, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1, 2, 3}, + AggSignature: bytes.Repeat([]byte{0}, BLSSignatureLength), + Timestamp: uint64(time.Now().Unix()), + }, true, "", }, diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go new file mode 100644 index 0000000000..a2b2fd4019 --- /dev/null +++ b/x/oracle/types/oracle.pb.go @@ -0,0 +1,303 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/oracle/v1/oracle.proto + +package types + +import ( + fmt "fmt" + _ "github.com/cosmos/cosmos-proto" + _ "github.com/gogo/protobuf/gogoproto" + 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 + +// Params holds parameters for the oracle module. +type Params struct { + RelayerTimeout uint64 `protobuf:"varint,1,opt,name=relayer_timeout,json=relayerTimeout,proto3" json:"relayer_timeout,omitempty"` +} + +func (m *Params) Reset() { *m = Params{} } +func (m *Params) String() string { return proto.CompactTextString(m) } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_3dec273964b5043c, []int{0} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.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 *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +func (m *Params) GetRelayerTimeout() uint64 { + if m != nil { + return m.RelayerTimeout + } + return 0 +} + +func init() { + proto.RegisterType((*Params)(nil), "cosmos.oracle.v1.Params") +} + +func init() { proto.RegisterFile("cosmos/oracle/v1/oracle.proto", fileDescriptor_3dec273964b5043c) } + +var fileDescriptor_3dec273964b5043c = []byte{ + // 185 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, + 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0x29, 0x91, 0xf4, + 0xfc, 0xf4, 0x7c, 0xb0, 0xa4, 0x3e, 0x88, 0x05, 0x51, 0x27, 0x25, 0x09, 0x51, 0x17, 0x0f, 0x91, + 0x80, 0x6a, 0x02, 0x73, 0x94, 0x0c, 0xb9, 0xd8, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x85, 0xd4, + 0xb9, 0xf8, 0x8b, 0x52, 0x73, 0x12, 0x2b, 0x53, 0x8b, 0xe2, 0x4b, 0x32, 0x73, 0x53, 0xf3, 0x4b, + 0x4b, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x82, 0xf8, 0xa0, 0xc2, 0x21, 0x10, 0x51, 0x27, 0xd7, + 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, 0x4e, 0xcf, 0x2c, 0xc9, 0x28, + 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85, 0xda, 0x02, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0x60, + 0xde, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x3b, 0xc0, 0x18, 0x10, 0x00, 0x00, 0xff, + 0xff, 0xba, 0x1f, 0x13, 0x83, 0xe4, 0x00, 0x00, 0x00, +} + +func (m *Params) 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 *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.RelayerTimeout != 0 { + i = encodeVarintOracle(dAtA, i, uint64(m.RelayerTimeout)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintOracle(dAtA []byte, offset int, v uint64) int { + offset -= sovOracle(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.RelayerTimeout != 0 { + n += 1 + sovOracle(uint64(m.RelayerTimeout)) + } + return n +} + +func sovOracle(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozOracle(x uint64) (n int) { + return sovOracle(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *Params) 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 ErrIntOverflowOracle + } + 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: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayerTimeout", wireType) + } + m.RelayerTimeout = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowOracle + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RelayerTimeout |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipOracle(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthOracle + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipOracle(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, ErrIntOverflowOracle + } + 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, ErrIntOverflowOracle + } + 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, ErrIntOverflowOracle + } + 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, ErrInvalidLengthOracle + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupOracle + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthOracle + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthOracle = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowOracle = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupOracle = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go new file mode 100644 index 0000000000..27a95c8c9c --- /dev/null +++ b/x/oracle/types/params.go @@ -0,0 +1,45 @@ +package types + +import ( + "fmt" + + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" +) + +const ( + DefaultRelayerTimeout uint64 = 5 * 60 // 5 minutes +) + +var ( + KeyParamRelayerTimeout = []byte("RelayerTimeout") +) + +func DefaultParams() Params { + return Params{ + RelayerTimeout: DefaultRelayerTimeout, + } +} + +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) +} + +// ParamSetPairs implements params.ParamSet +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(KeyParamRelayerTimeout, p.RelayerTimeout, validateRelayerTimeout), + } +} + +func validateRelayerTimeout(i interface{}) error { + v, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v <= 0 { + return fmt.Errorf("the relayer timeout must be positive: %d", v) + } + + return nil +} diff --git a/x/oracle/types/tx.pb.go b/x/oracle/types/tx.pb.go index d3d6e9c498..6a114d42e7 100644 --- a/x/oracle/types/tx.pb.go +++ b/x/oracle/types/tx.pb.go @@ -5,6 +5,7 @@ package types import ( context "context" + encoding_binary "encoding/binary" fmt "fmt" _ "github.com/cosmos/cosmos-proto" _ "github.com/cosmos/cosmos-sdk/types/msgservice" @@ -35,9 +36,10 @@ type MsgClaim struct { FromAddress string `protobuf:"bytes,1,opt,name=from_address,json=fromAddress,proto3" json:"from_address,omitempty"` ChainId uint32 `protobuf:"varint,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` - Payload []byte `protobuf:"bytes,4,opt,name=payload,proto3" json:"payload,omitempty"` - VoteAddressSet []uint64 `protobuf:"varint,5,rep,packed,name=vote_address_set,json=voteAddressSet,proto3" json:"vote_address_set,omitempty"` - AggSignature []byte `protobuf:"bytes,6,opt,name=agg_signature,json=aggSignature,proto3" json:"agg_signature,omitempty"` + Timestamp uint64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"` + VoteAddressSet []uint64 `protobuf:"fixed64,6,rep,packed,name=vote_address_set,json=voteAddressSet,proto3" json:"vote_address_set,omitempty"` + AggSignature []byte `protobuf:"bytes,7,opt,name=agg_signature,json=aggSignature,proto3" json:"agg_signature,omitempty"` } func (m *MsgClaim) Reset() { *m = MsgClaim{} } @@ -118,32 +120,33 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/tx.proto", fileDescriptor_836933fb4b988e66) } var fileDescriptor_836933fb4b988e66 = []byte{ - // 392 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xbf, 0xee, 0xd3, 0x30, - 0x10, 0xc7, 0xe3, 0xfe, 0xc7, 0xb4, 0xa8, 0xb2, 0x2a, 0xe1, 0x66, 0x48, 0xa3, 0xb2, 0x44, 0xa0, - 0x26, 0x2a, 0x6c, 0x30, 0x51, 0x06, 0xd4, 0xa1, 0x0c, 0xe9, 0xc6, 0x12, 0xb9, 0x89, 0x71, 0x23, - 0x9a, 0x38, 0xc4, 0x6e, 0xd5, 0xae, 0x9d, 0x18, 0x79, 0x84, 0x8e, 0x8c, 0x0c, 0x3c, 0x04, 0x63, - 0xc5, 0xc4, 0x88, 0xd2, 0x01, 0x1e, 0x03, 0x25, 0x8e, 0x91, 0x40, 0xfa, 0x4d, 0xf6, 0xdd, 0xe7, - 0xee, 0xab, 0xf3, 0x7d, 0x0d, 0xc7, 0x21, 0x17, 0x09, 0x17, 0x1e, 0xcf, 0x49, 0xb8, 0xa3, 0xde, - 0x61, 0xee, 0xc9, 0xa3, 0x9b, 0xe5, 0x5c, 0x72, 0x34, 0x54, 0xc8, 0x55, 0xc8, 0x3d, 0xcc, 0xcd, - 0x11, 0xe3, 0x8c, 0x57, 0xd0, 0x2b, 0x6f, 0xaa, 0xce, 0xac, 0x25, 0x02, 0x05, 0xea, 0x26, 0x85, - 0x1e, 0xd6, 0xea, 0x89, 0x60, 0xa5, 0x74, 0x22, 0x98, 0x02, 0xd3, 0x73, 0x03, 0xf6, 0x56, 0x82, - 0xbd, 0xda, 0x91, 0x38, 0x41, 0x2f, 0x60, 0xff, 0x5d, 0xce, 0x93, 0x80, 0x44, 0x51, 0x4e, 0x85, - 0xc0, 0xc0, 0x06, 0xce, 0xbd, 0x05, 0xfe, 0xfe, 0x75, 0x36, 0xaa, 0xd5, 0x5e, 0x2a, 0xb2, 0x96, - 0x79, 0x9c, 0x32, 0xff, 0x7e, 0x59, 0x5d, 0xa7, 0xd0, 0x18, 0xf6, 0xc2, 0x2d, 0x89, 0xd3, 0x20, - 0x8e, 0x70, 0xc3, 0x06, 0xce, 0xc0, 0xef, 0x56, 0xf1, 0x32, 0x42, 0x26, 0xec, 0x09, 0xfa, 0x61, - 0x4f, 0xd3, 0x90, 0xe2, 0xa6, 0x0d, 0x9c, 0x96, 0xff, 0x37, 0x46, 0x18, 0x76, 0x33, 0x72, 0xda, - 0x71, 0x12, 0xe1, 0x96, 0x0d, 0x9c, 0xbe, 0xaf, 0x43, 0xe4, 0xc0, 0xe1, 0x81, 0x4b, 0xaa, 0xa7, - 0x09, 0x04, 0x95, 0xb8, 0x6d, 0x37, 0x9d, 0x96, 0xff, 0xa0, 0xcc, 0xeb, 0x51, 0xa8, 0x44, 0x8f, - 0xe0, 0x80, 0x30, 0x16, 0x88, 0x98, 0xa5, 0x44, 0xee, 0x73, 0x8a, 0x3b, 0x95, 0x52, 0x9f, 0x30, - 0xb6, 0xd6, 0xb9, 0xe7, 0xe3, 0x8f, 0x97, 0x89, 0xf1, 0xfb, 0x32, 0x31, 0xce, 0xbf, 0xbe, 0x3c, - 0xfe, 0xe7, 0x9d, 0x53, 0x04, 0x87, 0x7a, 0x07, 0x3e, 0x15, 0x19, 0x4f, 0x05, 0x7d, 0xfa, 0x06, - 0x36, 0x57, 0x82, 0xa1, 0xd7, 0xb0, 0xad, 0x76, 0x63, 0xba, 0xff, 0xbb, 0xe0, 0xea, 0x1e, 0x73, - 0x7a, 0x37, 0xd3, 0x7a, 0x8b, 0xe5, 0xe7, 0xc2, 0x02, 0xdf, 0x0a, 0x0b, 0x5c, 0x0b, 0x0b, 0xfc, - 0x2c, 0x2c, 0xf0, 0xe9, 0x66, 0x19, 0xd7, 0x9b, 0x65, 0xfc, 0xb8, 0x59, 0xc6, 0xdb, 0x27, 0x2c, - 0x96, 0xdb, 0xfd, 0xc6, 0x0d, 0x79, 0x52, 0x1b, 0x57, 0x1f, 0x33, 0x11, 0xbd, 0xf7, 0x8e, 0xfa, - 0x57, 0xc8, 0x53, 0x46, 0xc5, 0xa6, 0x53, 0x59, 0xf7, 0xec, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xc1, 0x94, 0xe4, 0x54, 0x33, 0x02, 0x00, 0x00, + // 410 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x31, 0x6f, 0xd3, 0x40, + 0x14, 0xc7, 0x7d, 0x4d, 0x9b, 0xa4, 0x47, 0x8a, 0xa2, 0x53, 0x25, 0x2e, 0x16, 0x72, 0xad, 0xb0, + 0x58, 0xa0, 0xda, 0x2a, 0x6c, 0x30, 0x51, 0x06, 0xd4, 0xa1, 0x0c, 0xee, 0xc6, 0x62, 0x5d, 0xec, + 0xe3, 0x62, 0x91, 0xf3, 0x19, 0xbf, 0x4b, 0x94, 0xac, 0x4c, 0x8c, 0x7c, 0x84, 0x8c, 0x8c, 0x0c, + 0x7c, 0x08, 0xc6, 0x88, 0x89, 0x11, 0x39, 0x03, 0x7c, 0x0c, 0x64, 0x9f, 0x0f, 0x04, 0x52, 0x27, + 0xfb, 0xfd, 0x7f, 0xef, 0xfd, 0xf5, 0xf4, 0xfe, 0x87, 0x27, 0xa9, 0x02, 0xa9, 0x20, 0x52, 0x15, + 0x4b, 0x17, 0x3c, 0x5a, 0x5d, 0x44, 0x7a, 0x1d, 0x96, 0x95, 0xd2, 0x8a, 0x8c, 0x0d, 0x0a, 0x0d, + 0x0a, 0x57, 0x17, 0xee, 0xa9, 0x50, 0x42, 0xb5, 0x30, 0x6a, 0xfe, 0x4c, 0x9f, 0xdb, 0x59, 0x24, + 0x06, 0x74, 0x43, 0x06, 0xdd, 0xeb, 0xdc, 0x25, 0x88, 0xc6, 0x5a, 0x82, 0x30, 0x60, 0xba, 0x3d, + 0xc0, 0xc3, 0x6b, 0x10, 0x2f, 0x16, 0x2c, 0x97, 0xe4, 0x19, 0x1e, 0xbd, 0xa9, 0x94, 0x4c, 0x58, + 0x96, 0x55, 0x1c, 0x80, 0x22, 0x1f, 0x05, 0xc7, 0x97, 0xf4, 0xdb, 0x97, 0xf3, 0xd3, 0xce, 0xed, + 0xb9, 0x21, 0x37, 0xba, 0xca, 0x0b, 0x11, 0xdf, 0x69, 0xba, 0x3b, 0x89, 0x4c, 0xf0, 0x30, 0x9d, + 0xb3, 0xbc, 0x48, 0xf2, 0x8c, 0x1e, 0xf8, 0x28, 0x38, 0x89, 0x07, 0x6d, 0x7d, 0x95, 0x11, 0x17, + 0x0f, 0x81, 0xbf, 0x5b, 0xf2, 0x22, 0xe5, 0xb4, 0xe7, 0xa3, 0xe0, 0x30, 0xfe, 0x53, 0x93, 0xfb, + 0xf8, 0x58, 0xe7, 0x92, 0x83, 0x66, 0xb2, 0xa4, 0x87, 0x2d, 0xfc, 0x2b, 0x10, 0x8a, 0x07, 0x25, + 0xdb, 0x2c, 0x14, 0xcb, 0xe8, 0x91, 0x8f, 0x82, 0x51, 0x6c, 0x4b, 0x12, 0xe0, 0xf1, 0x4a, 0x69, + 0x6e, 0x77, 0x4d, 0x80, 0x6b, 0xda, 0xf7, 0x7b, 0x41, 0x3f, 0xbe, 0xdb, 0xe8, 0x76, 0x51, 0xae, + 0xc9, 0x03, 0x7c, 0xc2, 0x84, 0x48, 0x20, 0x17, 0x05, 0xd3, 0xcb, 0x8a, 0xd3, 0x41, 0xeb, 0x34, + 0x62, 0x42, 0xdc, 0x58, 0xed, 0xe9, 0xe4, 0xc3, 0xf6, 0xcc, 0xf9, 0xb5, 0x3d, 0x73, 0xde, 0xff, + 0xfc, 0xfc, 0xf0, 0x9f, 0x2b, 0x4c, 0x09, 0x1e, 0xdb, 0x0b, 0xc5, 0x1c, 0x4a, 0x55, 0x00, 0x7f, + 0xfc, 0x0a, 0xf7, 0xae, 0x41, 0x90, 0x97, 0xf8, 0xc8, 0x5c, 0xce, 0x0d, 0xff, 0xcf, 0x28, 0xb4, + 0x33, 0xee, 0xf4, 0x76, 0x66, 0xfd, 0x2e, 0xaf, 0x3e, 0xd5, 0x1e, 0xfa, 0x5a, 0x7b, 0x68, 0x57, + 0x7b, 0xe8, 0x47, 0xed, 0xa1, 0x8f, 0x7b, 0xcf, 0xd9, 0xed, 0x3d, 0xe7, 0xfb, 0xde, 0x73, 0x5e, + 0x3f, 0x12, 0xb9, 0x9e, 0x2f, 0x67, 0x61, 0xaa, 0x64, 0x17, 0x6b, 0xf7, 0x39, 0x87, 0xec, 0x6d, + 0xb4, 0xb6, 0x6f, 0x46, 0x6f, 0x4a, 0x0e, 0xb3, 0x7e, 0x1b, 0xec, 0x93, 0xdf, 0x01, 0x00, 0x00, + 0xff, 0xff, 0xb4, 0x46, 0xec, 0xf2, 0x51, 0x02, 0x00, 0x00, } func (this *MsgClaimResponse) Equal(that interface{}) bool { @@ -273,32 +276,28 @@ func (m *MsgClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { copy(dAtA[i:], m.AggSignature) i = encodeVarintTx(dAtA, i, uint64(len(m.AggSignature))) i-- - dAtA[i] = 0x32 + dAtA[i] = 0x3a } if len(m.VoteAddressSet) > 0 { - dAtA2 := make([]byte, len(m.VoteAddressSet)*10) - var j1 int - for _, num := range m.VoteAddressSet { - for num >= 1<<7 { - dAtA2[j1] = uint8(uint64(num)&0x7f | 0x80) - num >>= 7 - j1++ - } - dAtA2[j1] = uint8(num) - j1++ + for iNdEx := len(m.VoteAddressSet) - 1; iNdEx >= 0; iNdEx-- { + i -= 8 + encoding_binary.LittleEndian.PutUint64(dAtA[i:], uint64(m.VoteAddressSet[iNdEx])) } - i -= j1 - copy(dAtA[i:], dAtA2[:j1]) - i = encodeVarintTx(dAtA, i, uint64(j1)) + i = encodeVarintTx(dAtA, i, uint64(len(m.VoteAddressSet)*8)) i-- - dAtA[i] = 0x2a + dAtA[i] = 0x32 } if len(m.Payload) > 0 { i -= len(m.Payload) copy(dAtA[i:], m.Payload) i = encodeVarintTx(dAtA, i, uint64(len(m.Payload))) i-- - dAtA[i] = 0x22 + dAtA[i] = 0x2a + } + if m.Timestamp != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.Timestamp)) + i-- + dAtA[i] = 0x20 } if m.Sequence != 0 { i = encodeVarintTx(dAtA, i, uint64(m.Sequence)) @@ -370,16 +369,15 @@ func (m *MsgClaim) Size() (n int) { if m.Sequence != 0 { n += 1 + sovTx(uint64(m.Sequence)) } + if m.Timestamp != 0 { + n += 1 + sovTx(uint64(m.Timestamp)) + } l = len(m.Payload) if l > 0 { n += 1 + l + sovTx(uint64(l)) } if len(m.VoteAddressSet) > 0 { - l = 0 - for _, e := range m.VoteAddressSet { - l += sovTx(uint64(e)) - } - n += 1 + sovTx(uint64(l)) + l + n += 1 + sovTx(uint64(len(m.VoteAddressSet)*8)) + len(m.VoteAddressSet)*8 } l = len(m.AggSignature) if l > 0 { @@ -503,6 +501,25 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { } } case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) + } + m.Timestamp = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Timestamp |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 5: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) } @@ -536,23 +553,14 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { m.Payload = []byte{} } iNdEx = postIndex - case 5: - if wireType == 0 { + case 6: + if wireType == 1 { var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF } + v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 m.VoteAddressSet = append(m.VoteAddressSet, v) } else if wireType == 2 { var packedLen int @@ -581,38 +589,23 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { return io.ErrUnexpectedEOF } var elementCount int - var count int - for _, integer := range dAtA[iNdEx:postIndex] { - if integer < 128 { - count++ - } - } - elementCount = count + elementCount = packedLen / 8 if elementCount != 0 && len(m.VoteAddressSet) == 0 { m.VoteAddressSet = make([]uint64, 0, elementCount) } for iNdEx < postIndex { var v uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTx - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - v |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } + if (iNdEx + 8) > l { + return io.ErrUnexpectedEOF } + v = uint64(encoding_binary.LittleEndian.Uint64(dAtA[iNdEx:])) + iNdEx += 8 m.VoteAddressSet = append(m.VoteAddressSet, v) } } else { return fmt.Errorf("proto: wrong wireType = %d for field VoteAddressSet", wireType) } - case 6: + case 7: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AggSignature", wireType) } From 4540635e443858392cc28ce3e8423ccf859c6f1a Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 28 Nov 2022 19:14:38 +0800 Subject: [PATCH 09/50] refactor the check for the inturn relayer --- proto/cosmos/oracle/v1/oracle.proto | 3 +- proto/cosmos/oracle/v1/query.proto | 1 - x/oracle/keeper/keeper.go | 43 +++++--- x/oracle/keeper/keeper_test.go | 161 ++++++++++++++++++++++++++++ x/oracle/types/msgs_test.go | 3 +- x/oracle/types/oracle.pb.go | 55 ++++++++-- x/oracle/types/params.go | 23 +++- x/oracle/types/query.pb.go | 17 ++- 8 files changed, 268 insertions(+), 38 deletions(-) create mode 100644 x/oracle/keeper/keeper_test.go diff --git a/proto/cosmos/oracle/v1/oracle.proto b/proto/cosmos/oracle/v1/oracle.proto index c401a0ad6b..f406f2e768 100644 --- a/proto/cosmos/oracle/v1/oracle.proto +++ b/proto/cosmos/oracle/v1/oracle.proto @@ -8,5 +8,6 @@ import "cosmos_proto/cosmos.proto"; // Params holds parameters for the oracle module. message Params { - uint64 relayer_timeout = 1; + uint64 relayer_timeout = 1; // in s + uint64 relayer_backoff_time = 2; // in s } diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto index d89610138b..0da5f8ca38 100644 --- a/proto/cosmos/oracle/v1/query.proto +++ b/proto/cosmos/oracle/v1/query.proto @@ -3,7 +3,6 @@ package cosmos.crosschain.v1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; -import "cosmos/crosschain/v1/oracle.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 39a85ef433..9b0cf07324 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -4,6 +4,9 @@ import ( "fmt" sdkerrors "cosmossdk.io/errors" + "github.com/prysmaticlabs/prysm/crypto/bls" + "github.com/willf/bitset" + "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -11,8 +14,6 @@ import ( "github.com/cosmos/cosmos-sdk/x/oracle/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - "github.com/prysmaticlabs/prysm/crypto/bls" - "github.com/willf/bitset" ) type Keeper struct { @@ -51,17 +52,24 @@ func NewKeeper( } } -// GetRelayerTimeoutParam returns the default relayer timeout for oracle claim -func (k Keeper) GetRelayerTimeoutParam(ctx sdk.Context) uint64 { +// SetParams sets the params of oarcle module +func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { + k.paramSpace.SetParamSet(ctx, ¶ms) +} + +// GetRelayerParam returns the relayer timeout and backoff time for oracle claim +func (k Keeper) GetRelayerParam(ctx sdk.Context) (uint64, uint64) { var relayerTimeoutParam uint64 + var relayerBackoffTimeParam uint64 k.paramSpace.Get(ctx, types.KeyParamRelayerTimeout, &relayerTimeoutParam) - return relayerTimeoutParam + k.paramSpace.Get(ctx, types.KeyParamRelayerBackoffTime, &relayerBackoffTimeParam) + return relayerTimeoutParam, relayerBackoffTimeParam } -func (k Keeper) isValidatorInTurn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { +func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { var validatorIndex int64 = -1 for index, validator := range validators { - consAddr, err := validator.GetConsAddr() + consAddr, err := validator.GetConsAddr() // TODO: update this if err != nil { return false, err } @@ -75,23 +83,30 @@ func (k Keeper) isValidatorInTurn(ctx sdk.Context, validators []stakingtypes.Val return false, sdkerrors.Wrapf(types.ErrNotValidator, fmt.Sprintf("sender is not validator")) } + // check inturn validator index + inturnValidatorIndex := claim.Timestamp % uint64(len(validators)) + curTime := ctx.BlockTime().Unix() - relayerTimeout := k.GetRelayerTimeoutParam(ctx) + relayerTimeout, relayerBackoffTime := k.GetRelayerParam(ctx) + // check block time with package timestamp - if uint64(curTime)-claim.Timestamp > relayerTimeout { - return true, nil + if uint64(curTime)-claim.Timestamp <= relayerTimeout { + if uint64(validatorIndex) == inturnValidatorIndex { + return true, nil + } + return false, nil } - // check inturn validator index - inturnValidatorIndex := claim.Timestamp % uint64(len(validators)) - return uint64(validatorIndex) == inturnValidatorIndex, nil + backoffIndex := (uint64(curTime)-claim.Timestamp-relayerTimeout-1)/relayerBackoffTime + 1 + + return uint64(validatorIndex) == (inturnValidatorIndex+backoffIndex)%uint64(len(validators)), nil } // ProcessClaim checks the bls signature func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { validators := k.StakingKeeper.GetLastValidators(ctx) - inturn, err := k.isValidatorInTurn(ctx, validators, claim) + inturn, err := k.IsValidatorInturn(ctx, validators, claim) if err != nil { return err } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go new file mode 100644 index 0000000000..7475f2002c --- /dev/null +++ b/x/oracle/keeper/keeper_test.go @@ -0,0 +1,161 @@ +package keeper_test + +import ( + "testing" + "time" + + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" + + "github.com/stretchr/testify/require" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtime "github.com/tendermint/tendermint/types/time" + + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/simapp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" +) + +type TestSuite struct { + suite.Suite + + app *simapp.SimApp + ctx sdk.Context +} + +func (s *TestSuite) SetupTest() { + app := simapp.Setup(s.T(), false) + ctx := app.BaseApp.NewContext(false, tmproto.Header{}) + ctx = ctx.WithBlockHeader(tmproto.Header{Time: tmtime.Now()}) + + app.OracleKeeper.SetParams(ctx, types.DefaultParams()) + + s.app = app + s.ctx = ctx +} + +func TestTestSuite(t *testing.T) { + suite.Run(t, new(TestSuite)) +} + +func (s *TestSuite) TestKeeper_IsValidatorInturn() { + s.app.OracleKeeper.SetParams(s.ctx, types.Params{ + RelayerTimeout: 5, + RelayerBackoffTime: 3, + }) + + vals := make([]stakingtypes.Validator, 5) + for i := range vals { + pk := ed25519.GenPrivKey().PubKey() + vals[i] = newValidator(s.T(), sdk.ValAddress(pk.Address()), pk) + } + + val0Addr, err := vals[0].GetConsAddr() + s.Require().Nil(err) + val1Addr, err := vals[1].GetConsAddr() + s.Require().Nil(err) + + tests := []struct { + claimMsg types.MsgClaim + blockTime int64 + expectedPass bool + errorMsg string + }{ + { + types.MsgClaim{ + FromAddress: val0Addr.String(), + ChainId: 1, + Sequence: 1, + Timestamp: 1990, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + 1992, + true, + "", + }, + // wrong validator in timeout + { + types.MsgClaim{ + FromAddress: val1Addr.String(), + ChainId: 1, + Sequence: 1, + Timestamp: 1990, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + 1992, + false, + "", + }, + // right validator in backoff time + { + types.MsgClaim{ + FromAddress: val1Addr.String(), + ChainId: 1, + Sequence: 1, + Timestamp: 1985, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + 1992, + true, + "", + }, + // wrong validator in backoff time + { + types.MsgClaim{ + FromAddress: val0Addr.String(), + ChainId: 1, + Sequence: 1, + Timestamp: 1985, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + 1992, + false, + "", + }, + // right validator in backoff time + { + types.MsgClaim{ + FromAddress: val0Addr.String(), + ChainId: 1, + Sequence: 1, + Timestamp: 1970, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + 1989, + true, + "", + }, + } + + for _, test := range tests { + s.ctx = s.ctx.WithBlockTime(time.Unix(test.blockTime, 0)) + isInturn, err := s.app.OracleKeeper.IsValidatorInturn(s.ctx, vals, &test.claimMsg) + + if test.expectedPass { + s.Require().Nil(err) + s.Require().True(isInturn) + } else { + s.Require().False(isInturn) + } + } + +} + +// Creates a new validators and asserts the error check. +func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) stakingtypes.Validator { + v, err := stakingtypes.NewValidator(operator, pubKey, stakingtypes.Description{}) + require.NoError(t, err) + return v +} diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index eb4fc03e22..1c1dcfd691 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -8,10 +8,11 @@ import ( "testing" "time" + "github.com/stretchr/testify/require" + "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil" - "github.com/stretchr/testify/require" ) func TestBlsClaim(t *testing.T) { diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go index a2b2fd4019..d584f7d0fb 100644 --- a/x/oracle/types/oracle.pb.go +++ b/x/oracle/types/oracle.pb.go @@ -26,7 +26,8 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the oracle module. type Params struct { - RelayerTimeout uint64 `protobuf:"varint,1,opt,name=relayer_timeout,json=relayerTimeout,proto3" json:"relayer_timeout,omitempty"` + RelayerTimeout uint64 `protobuf:"varint,1,opt,name=relayer_timeout,json=relayerTimeout,proto3" json:"relayer_timeout,omitempty"` + RelayerBackoffTime uint64 `protobuf:"varint,2,opt,name=relayer_backoff_time,json=relayerBackoffTime,proto3" json:"relayer_backoff_time,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -69,6 +70,13 @@ func (m *Params) GetRelayerTimeout() uint64 { return 0 } +func (m *Params) GetRelayerBackoffTime() uint64 { + if m != nil { + return m.RelayerBackoffTime + } + return 0 +} + func init() { proto.RegisterType((*Params)(nil), "cosmos.oracle.v1.Params") } @@ -76,19 +84,21 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/oracle.proto", fileDescriptor_3dec273964b5043c) } var fileDescriptor_3dec273964b5043c = []byte{ - // 185 bytes of a gzipped FileDescriptorProto + // 212 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0x29, 0x91, 0xf4, 0xfc, 0xf4, 0x7c, 0xb0, 0xa4, 0x3e, 0x88, 0x05, 0x51, 0x27, 0x25, 0x09, 0x51, 0x17, 0x0f, 0x91, - 0x80, 0x6a, 0x02, 0x73, 0x94, 0x0c, 0xb9, 0xd8, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x85, 0xd4, + 0x80, 0x6a, 0x02, 0x73, 0x94, 0x92, 0xb9, 0xd8, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x85, 0xd4, 0xb9, 0xf8, 0x8b, 0x52, 0x73, 0x12, 0x2b, 0x53, 0x8b, 0xe2, 0x4b, 0x32, 0x73, 0x53, 0xf3, 0x4b, - 0x4b, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x82, 0xf8, 0xa0, 0xc2, 0x21, 0x10, 0x51, 0x27, 0xd7, - 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, 0x4e, 0xcf, 0x2c, 0xc9, 0x28, - 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0x85, 0xda, 0x02, 0xa5, 0x74, 0x8b, 0x53, 0xb2, 0xf5, 0x2b, 0x60, - 0xde, 0x28, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x3b, 0xc0, 0x18, 0x10, 0x00, 0x00, 0xff, - 0xff, 0xba, 0x1f, 0x13, 0x83, 0xe4, 0x00, 0x00, 0x00, + 0x4b, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x82, 0xf8, 0xa0, 0xc2, 0x21, 0x10, 0x51, 0x21, 0x03, + 0x2e, 0x11, 0x98, 0xc2, 0xa4, 0xc4, 0xe4, 0xec, 0xfc, 0xb4, 0x34, 0xb0, 0x06, 0x09, 0x26, 0xb0, + 0x6a, 0x21, 0xa8, 0x9c, 0x13, 0x44, 0x0a, 0xa4, 0xc9, 0xc9, 0xf5, 0xc4, 0x23, 0x39, 0xc6, 0x0b, + 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, + 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xb4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, + 0xa1, 0xee, 0x82, 0x52, 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x15, 0x30, 0x8f, 0x97, 0x54, 0x16, 0xa4, + 0x16, 0x27, 0xb1, 0x81, 0x9d, 0x6c, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xe1, 0x78, 0xe6, 0x29, + 0x16, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -111,6 +121,11 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.RelayerBackoffTime != 0 { + i = encodeVarintOracle(dAtA, i, uint64(m.RelayerBackoffTime)) + i-- + dAtA[i] = 0x10 + } if m.RelayerTimeout != 0 { i = encodeVarintOracle(dAtA, i, uint64(m.RelayerTimeout)) i-- @@ -139,6 +154,9 @@ func (m *Params) Size() (n int) { if m.RelayerTimeout != 0 { n += 1 + sovOracle(uint64(m.RelayerTimeout)) } + if m.RelayerBackoffTime != 0 { + n += 1 + sovOracle(uint64(m.RelayerBackoffTime)) + } return n } @@ -196,6 +214,25 @@ func (m *Params) Unmarshal(dAtA []byte) error { break } } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayerBackoffTime", wireType) + } + m.RelayerBackoffTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowOracle + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RelayerBackoffTime |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipOracle(dAtA[iNdEx:]) diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 27a95c8c9c..96c3c9998e 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -7,16 +7,19 @@ import ( ) const ( - DefaultRelayerTimeout uint64 = 5 * 60 // 5 minutes + DefaultRelayerTimeout uint64 = 40 // in s + DefaultRelayerBackoffTime uint64 = 5 // in s ) var ( - KeyParamRelayerTimeout = []byte("RelayerTimeout") + KeyParamRelayerTimeout = []byte("RelayerTimeout") + KeyParamRelayerBackoffTime = []byte("RelayerBackoffTime") ) func DefaultParams() Params { return Params{ - RelayerTimeout: DefaultRelayerTimeout, + RelayerTimeout: DefaultRelayerTimeout, + RelayerBackoffTime: DefaultRelayerBackoffTime, } } @@ -28,6 +31,7 @@ func ParamKeyTable() paramtypes.KeyTable { func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyParamRelayerTimeout, p.RelayerTimeout, validateRelayerTimeout), + paramtypes.NewParamSetPair(KeyParamRelayerBackoffTime, p.RelayerBackoffTime, validateRelayerBackoffTime), } } @@ -43,3 +47,16 @@ func validateRelayerTimeout(i interface{}) error { return nil } + +func validateRelayerBackoffTime(i interface{}) error { + v, ok := i.(uint64) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v <= 0 { + return fmt.Errorf("the relayer backoff time must be positive: %d", v) + } + + return nil +} diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index 98679cfd06..2698b26b52 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -6,7 +6,6 @@ package types import ( context "context" fmt "fmt" - _ "github.com/cosmos/cosmos-sdk/x/crosschain/types" _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" @@ -29,19 +28,19 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func init() { proto.RegisterFile("cosmos/oracle/v1/query.proto", fileDescriptor_9f804c4644f3aaef) } var fileDescriptor_9f804c4644f3aaef = []byte{ - // 192 bytes of a gzipped FileDescriptorProto + // 180 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xc8, 0xea, 0x25, 0x17, 0xe5, 0x17, 0x17, 0x27, 0x67, 0x24, 0x66, 0xe6, 0xe9, 0x95, 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x32, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, - 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x89, 0x25, 0x99, 0xf9, 0x79, 0xc5, 0x50, - 0x59, 0x55, 0xa8, 0x3d, 0x08, 0x93, 0x40, 0x76, 0x21, 0x99, 0x0b, 0x56, 0x66, 0xc4, 0xce, 0xc5, - 0x1a, 0x08, 0xb2, 0xdf, 0xc9, 0xf5, 0xc4, 0x23, 0x39, 0xc6, 0x0b, 0x8f, 0xe4, 0x18, 0x1f, 0x3c, - 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, 0x1b, 0x8f, 0xe5, 0x18, 0xa2, - 0xb4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, 0xf5, 0x61, 0x86, 0x82, 0x29, - 0xdd, 0xe2, 0x94, 0x6c, 0xfd, 0x0a, 0x98, 0x4f, 0x4a, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, - 0xc6, 0x1a, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x37, 0xc8, 0x15, 0xcf, 0xe7, 0x00, 0x00, 0x00, + 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x89, 0x25, 0x99, 0xf9, 0x79, 0xc5, 0x10, + 0x59, 0x23, 0x76, 0x2e, 0xd6, 0x40, 0x90, 0xc1, 0x4e, 0xae, 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, 0x9d, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, + 0x0f, 0x75, 0x15, 0x84, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, 0x80, 0x39, 0xb1, 0xa4, 0xb2, 0x20, + 0xb5, 0x38, 0x89, 0x0d, 0x6c, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xa0, 0xa2, 0x54, 0xe6, + 0xc0, 0x00, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. From 0a51cb3248b421aa97548e88d09f476c6afd5a67 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 28 Nov 2022 20:29:49 +0800 Subject: [PATCH 10/50] remove pegaccount for cross chain module --- types/cross_chain.go | 6 ------ x/oracle/keeper/keeper.go | 8 +++++--- x/oracle/keeper/msg_server.go | 5 +++-- x/oracle/types/expected_keepers.go | 2 +- 4 files changed, 9 insertions(+), 12 deletions(-) diff --git a/types/cross_chain.go b/types/cross_chain.go index de26d50a90..2cab476073 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -6,12 +6,6 @@ import ( "math" "math/big" "strconv" - - "github.com/tendermint/tendermint/crypto" -) - -var ( - PegAccount = AccAddress(crypto.AddressHash([]byte("BFSPegAccount"))) // TODO: update if needed ) type CrossChainPackageType uint8 diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 9b0cf07324..a63f56fdb9 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -3,6 +3,8 @@ package keeper import ( "fmt" + crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" + sdkerrors "cosmossdk.io/errors" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/willf/bitset" @@ -152,7 +154,7 @@ func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { return nil } -// SendCoinsFromAccountToFeeCollector transfers amt to the fee collector account. -func (k Keeper) SendCoinsFromAccountToFeeCollector(ctx sdk.Context, senderAddr sdk.AccAddress, amt sdk.Coins) error { - return k.BankKeeper.SendCoinsFromAccountToModule(ctx, senderAddr, k.feeCollectorName, amt) +// SendCoinsToFeeCollector transfers amt to the fee collector account. +func (k Keeper) SendCoinsToFeeCollector(ctx sdk.Context, amt sdk.Coins) error { + return k.BankKeeper.SendCoinsFromModuleToModule(ctx, crosschaintypes.ModuleName, k.feeCollectorName, amt) } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index d68cd78851..033001534c 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -7,10 +7,11 @@ import ( "runtime/debug" sdkerrors "cosmossdk.io/errors" + "github.com/gogo/protobuf/proto" + "github.com/cosmos/cosmos-sdk/bsc/rlp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/oracle/types" - "github.com/gogo/protobuf/proto" ) type msgServer struct { @@ -101,7 +102,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch } fee := sdk.Coins{sdk.Coin{Denom: sdk.NativeTokenSymbol, Amount: sdk.NewInt(feeAmount)}} - err = oracleKeeper.SendCoinsFromAccountToFeeCollector(ctx, sdk.PegAccount, fee) + err = oracleKeeper.SendCoinsToFeeCollector(ctx, fee) if err != nil { return nil, err } diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 73d08c1199..f51ef290a4 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -18,5 +18,5 @@ type CrossChainKeeper interface { } type BankKeeper interface { - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error } From 96be0f3bf0112e5c50e1e1853599e8250b87a8c5 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 5 Dec 2022 17:53:25 +0800 Subject: [PATCH 11/50] fix comments --- bsc/rate.go | 31 ------ proto/cosmos/crosschain/v1/crosschain.proto | 2 +- proto/cosmos/crosschain/v1/event.proto | 2 +- x/crosschain/keeper/config.go | 18 ++-- x/crosschain/keeper/keeper.go | 38 +++----- x/crosschain/keeper/keeper_test.go | 14 +-- x/crosschain/types/crosschain.pb.go | 42 +++++--- x/crosschain/types/event.pb.go | 103 ++++++++++---------- x/crosschain/types/params.go | 16 ++- x/oracle/keeper/keeper.go | 3 +- 10 files changed, 120 insertions(+), 149 deletions(-) delete mode 100644 bsc/rate.go diff --git a/bsc/rate.go b/bsc/rate.go deleted file mode 100644 index bdab0343d4..0000000000 --- a/bsc/rate.go +++ /dev/null @@ -1,31 +0,0 @@ -package bsc - -import ( - "math" - "math/big" -) - -const ( - BNBDecimalOnBFS = 8 - BNBDecimalOnBSC = 18 -) - -func GetBigIntForDecimal(decimal int) *big.Int { - floatDecimal := big.NewFloat(math.Pow10(decimal)) - bigIntDecimal := new(big.Int) - floatDecimal.Int(bigIntDecimal) - - return bigIntDecimal -} - -// ConvertBCAmountToBSCAmount can only be used to convert BNB decimal -func ConvertBCAmountToBSCAmount(bcAmount int64) *big.Int { - decimals := GetBigIntForDecimal(BNBDecimalOnBSC - BNBDecimalOnBFS) - return big.NewInt(0).Mul(big.NewInt(bcAmount), decimals) -} - -// ConvertBSCAmountToBCAmount can only be used to convert BNB decimal -func ConvertBSCAmountToBCAmount(bscAmount *big.Int) int64 { - decimals := GetBigIntForDecimal(BNBDecimalOnBSC - BNBDecimalOnBFS) - return big.NewInt(0).Div(bscAmount, decimals).Int64() -} diff --git a/proto/cosmos/crosschain/v1/crosschain.proto b/proto/cosmos/crosschain/v1/crosschain.proto index 36c6cc6e0a..8508864dba 100644 --- a/proto/cosmos/crosschain/v1/crosschain.proto +++ b/proto/cosmos/crosschain/v1/crosschain.proto @@ -8,5 +8,5 @@ import "cosmos_proto/cosmos.proto"; // Params holds parameters for the cross chain module. message Params { - uint64 relayer_fee = 1; + string relayer_fee = 1; } diff --git a/proto/cosmos/crosschain/v1/event.proto b/proto/cosmos/crosschain/v1/event.proto index 8df6ddb7b1..11a695088a 100644 --- a/proto/cosmos/crosschain/v1/event.proto +++ b/proto/cosmos/crosschain/v1/event.proto @@ -6,7 +6,7 @@ import "cosmos_proto/cosmos.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; -message EventCrossChainPackage { +message EventCrossChain { uint32 src_chain_id = 1; uint32 dest_chain_id = 2; uint32 channel_id = 3; diff --git a/x/crosschain/keeper/config.go b/x/crosschain/keeper/config.go index f2ac20c70b..53348aa8ff 100644 --- a/x/crosschain/keeper/config.go +++ b/x/crosschain/keeper/config.go @@ -5,22 +5,22 @@ import sdk "github.com/cosmos/cosmos-sdk/types" type crossChainConfig struct { srcChainID sdk.ChainID + destChains []sdk.ChainID + nameToChannelID map[string]sdk.ChannelID channelIDToName map[sdk.ChannelID]string channelIDToApp map[sdk.ChannelID]sdk.CrossChainApplication - - destChainNameToID map[string]sdk.ChainID - destChainIDToName map[sdk.ChainID]string } func newCrossChainCfg() *crossChainConfig { config := &crossChainConfig{ - srcChainID: 0, - nameToChannelID: make(map[string]sdk.ChannelID), - channelIDToName: make(map[sdk.ChannelID]string), - destChainNameToID: make(map[string]sdk.ChainID), - destChainIDToName: make(map[sdk.ChainID]string), - channelIDToApp: make(map[sdk.ChannelID]sdk.CrossChainApplication), + srcChainID: 0, + + destChains: make([]sdk.ChainID, 0), + + nameToChannelID: make(map[string]sdk.ChannelID), + channelIDToName: make(map[sdk.ChannelID]string), + channelIDToApp: make(map[sdk.ChannelID]sdk.CrossChainApplication), } return config } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 978f2858bd..abf9e84c38 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -7,7 +7,6 @@ import ( "github.com/tendermint/tendermint/libs/log" - "github.com/cosmos/cosmos-sdk/bsc" "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -48,10 +47,13 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { // GetRelayerFeeParam returns the default relayer fee for cross chain tx func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { - var relayerFeeParam uint64 + var relayerFeeParam string k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) - relayerFee = bsc.ConvertBCAmountToBSCAmount(int64(relayerFeeParam)) - return + relayerFee, valid := relayerFee.SetString(relayerFeeParam, 10) + if !valid { + return nil, fmt.Errorf("invalid relayer fee: %s", relayerFeeParam) + } + return relayerFee, nil } // SetParams sets the params of cross chain module @@ -93,7 +95,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai k.IncrSendSequence(ctx, destChainID, channelID) - err := ctx.EventManager().EmitTypedEvent(&types.EventCrossChainPackage{ + err := ctx.EventManager().EmitTypedEvent(&types.EventCrossChain{ SrcChainId: uint32(k.GetSrcChainID()), DestChainId: uint32(destChainID), ChannelId: uint32(channelID), @@ -130,17 +132,14 @@ func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChai } // RegisterDestChain registers a chain with name -func (k Keeper) RegisterDestChain(name string, chainID sdk.ChainID) error { - _, ok := k.cfg.destChainNameToID[name] - if ok { - return fmt.Errorf("duplicated destination chain name") - } - _, ok = k.cfg.destChainIDToName[chainID] - if ok { - return fmt.Errorf("duplicated destination chain chainID") +func (k Keeper) RegisterDestChain(chainID sdk.ChainID) error { + for _, chain := range k.cfg.destChains { + if chainID == chain { + return fmt.Errorf("duplicated destination chain chainID") + } } - k.cfg.destChainNameToID[name] = chainID - k.cfg.destChainIDToName[chainID] = name + + k.cfg.destChains = append(k.cfg.destChains, chainID) return nil } @@ -170,15 +169,6 @@ func (k Keeper) GetSrcChainID() sdk.ChainID { return k.cfg.srcChainID } -// GetDestChainID returns the chain id by name -func (k Keeper) GetDestChainID(name string) (sdk.ChainID, error) { - destChainID, exist := k.cfg.destChainNameToID[name] - if !exist { - return sdk.ChainID(0), fmt.Errorf("non-existing destination chainName ") - } - return destChainID, nil -} - // GetIBCPackage returns the ibc package by sequence func (k Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { kvStore := ctx.KVStore(k.storeKey) diff --git a/x/crosschain/keeper/keeper_test.go b/x/crosschain/keeper/keeper_test.go index e73f64b10f..036a08869b 100644 --- a/x/crosschain/keeper/keeper_test.go +++ b/x/crosschain/keeper/keeper_test.go @@ -55,24 +55,14 @@ func (s *TestSuite) TestIncrReceiveSequence() { } func (s *TestSuite) TestRegisterDestChain() { - testName := "test" testChainId := sdk.ChainID(100) - err := s.app.CrossChainKeeper.RegisterDestChain(testName, testChainId) + err := s.app.CrossChainKeeper.RegisterDestChain(testChainId) s.Require().NoError(err) - chainId, err := s.app.CrossChainKeeper.GetDestChainID(testName) - s.Require().NoError(err) - - s.Require().EqualValues(chainId, testChainId) - - // check duplicate name - err = s.app.CrossChainKeeper.RegisterDestChain(testName, testChainId) - s.Require().ErrorContains(err, "duplicated destination chain name") - // check duplicate channel id - err = s.app.CrossChainKeeper.RegisterDestChain("another chain", testChainId) + err = s.app.CrossChainKeeper.RegisterDestChain(testChainId) s.Require().ErrorContains(err, "duplicated destination chain chainID") } diff --git a/x/crosschain/types/crosschain.pb.go b/x/crosschain/types/crosschain.pb.go index a1faabfc13..76e0c8da43 100644 --- a/x/crosschain/types/crosschain.pb.go +++ b/x/crosschain/types/crosschain.pb.go @@ -26,7 +26,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the cross chain module. type Params struct { - RelayerFee uint64 `protobuf:"varint,1,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` + RelayerFee string `protobuf:"bytes,1,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -62,11 +62,11 @@ func (m *Params) XXX_DiscardUnknown() { var xxx_messageInfo_Params proto.InternalMessageInfo -func (m *Params) GetRelayerFee() uint64 { +func (m *Params) GetRelayerFee() string { if m != nil { return m.RelayerFee } - return 0 + return "" } func init() { @@ -85,12 +85,12 @@ var fileDescriptor_d7b94a7254cf916a = []byte{ 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x92, 0x10, 0xb5, 0xf1, 0x10, 0x09, 0xa8, 0x46, 0x30, 0x47, 0x49, 0x93, 0x8b, 0x2d, 0x20, 0xb1, 0x28, 0x31, 0xb7, 0x58, 0x48, 0x9e, 0x8b, 0xbb, 0x28, 0x35, 0x27, 0xb1, 0x32, 0xb5, 0x28, 0x3e, 0x2d, - 0x35, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x25, 0x88, 0x0b, 0x2a, 0xe4, 0x96, 0x9a, 0xea, 0xe4, + 0x35, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x88, 0x0b, 0x2a, 0xe4, 0x96, 0x9a, 0xea, 0xe4, 0x79, 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, 0xfa, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x30, 0xd7, 0x83, 0x29, 0xdd, 0xe2, 0x94, 0x6c, 0xfd, 0x0a, 0x64, 0xaf, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x2d, 0x37, 0x06, 0x04, 0x00, - 0x00, 0xff, 0xff, 0xd1, 0xfd, 0x76, 0x86, 0xec, 0x00, 0x00, 0x00, + 0x00, 0xff, 0xff, 0xcc, 0x3a, 0x09, 0xdd, 0xec, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -113,10 +113,12 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.RelayerFee != 0 { - i = encodeVarintCrosschain(dAtA, i, uint64(m.RelayerFee)) + if len(m.RelayerFee) > 0 { + i -= len(m.RelayerFee) + copy(dAtA[i:], m.RelayerFee) + i = encodeVarintCrosschain(dAtA, i, uint64(len(m.RelayerFee))) i-- - dAtA[i] = 0x8 + dAtA[i] = 0xa } return len(dAtA) - i, nil } @@ -138,8 +140,9 @@ func (m *Params) Size() (n int) { } var l int _ = l - if m.RelayerFee != 0 { - n += 1 + sovCrosschain(uint64(m.RelayerFee)) + l = len(m.RelayerFee) + if l > 0 { + n += 1 + l + sovCrosschain(uint64(l)) } return n } @@ -180,10 +183,10 @@ func (m *Params) Unmarshal(dAtA []byte) error { } switch fieldNum { case 1: - if wireType != 0 { + if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RelayerFee", wireType) } - m.RelayerFee = 0 + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowCrosschain @@ -193,11 +196,24 @@ func (m *Params) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.RelayerFee |= uint64(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthCrosschain + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCrosschain + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RelayerFee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCrosschain(dAtA[iNdEx:]) diff --git a/x/crosschain/types/event.pb.go b/x/crosschain/types/event.pb.go index b8592900e6..3abfacc51b 100644 --- a/x/crosschain/types/event.pb.go +++ b/x/crosschain/types/event.pb.go @@ -23,7 +23,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package -type EventCrossChainPackage struct { +type EventCrossChain struct { SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` @@ -34,18 +34,18 @@ type EventCrossChainPackage struct { RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` } -func (m *EventCrossChainPackage) Reset() { *m = EventCrossChainPackage{} } -func (m *EventCrossChainPackage) String() string { return proto.CompactTextString(m) } -func (*EventCrossChainPackage) ProtoMessage() {} -func (*EventCrossChainPackage) Descriptor() ([]byte, []int) { +func (m *EventCrossChain) Reset() { *m = EventCrossChain{} } +func (m *EventCrossChain) String() string { return proto.CompactTextString(m) } +func (*EventCrossChain) ProtoMessage() {} +func (*EventCrossChain) Descriptor() ([]byte, []int) { return fileDescriptor_2a5a3ba75f5dd2c3, []int{0} } -func (m *EventCrossChainPackage) XXX_Unmarshal(b []byte) error { +func (m *EventCrossChain) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *EventCrossChainPackage) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *EventCrossChain) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_EventCrossChainPackage.Marshal(b, m, deterministic) + return xxx_messageInfo_EventCrossChain.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -55,68 +55,68 @@ func (m *EventCrossChainPackage) XXX_Marshal(b []byte, deterministic bool) ([]by return b[:n], nil } } -func (m *EventCrossChainPackage) XXX_Merge(src proto.Message) { - xxx_messageInfo_EventCrossChainPackage.Merge(m, src) +func (m *EventCrossChain) XXX_Merge(src proto.Message) { + xxx_messageInfo_EventCrossChain.Merge(m, src) } -func (m *EventCrossChainPackage) XXX_Size() int { +func (m *EventCrossChain) XXX_Size() int { return m.Size() } -func (m *EventCrossChainPackage) XXX_DiscardUnknown() { - xxx_messageInfo_EventCrossChainPackage.DiscardUnknown(m) +func (m *EventCrossChain) XXX_DiscardUnknown() { + xxx_messageInfo_EventCrossChain.DiscardUnknown(m) } -var xxx_messageInfo_EventCrossChainPackage proto.InternalMessageInfo +var xxx_messageInfo_EventCrossChain proto.InternalMessageInfo -func (m *EventCrossChainPackage) GetSrcChainId() uint32 { +func (m *EventCrossChain) GetSrcChainId() uint32 { if m != nil { return m.SrcChainId } return 0 } -func (m *EventCrossChainPackage) GetDestChainId() uint32 { +func (m *EventCrossChain) GetDestChainId() uint32 { if m != nil { return m.DestChainId } return 0 } -func (m *EventCrossChainPackage) GetChannelId() uint32 { +func (m *EventCrossChain) GetChannelId() uint32 { if m != nil { return m.ChannelId } return 0 } -func (m *EventCrossChainPackage) GetSequence() uint64 { +func (m *EventCrossChain) GetSequence() uint64 { if m != nil { return m.Sequence } return 0 } -func (m *EventCrossChainPackage) GetPackageType() uint32 { +func (m *EventCrossChain) GetPackageType() uint32 { if m != nil { return m.PackageType } return 0 } -func (m *EventCrossChainPackage) GetTimestamp() uint64 { +func (m *EventCrossChain) GetTimestamp() uint64 { if m != nil { return m.Timestamp } return 0 } -func (m *EventCrossChainPackage) GetPackageLoad() []byte { +func (m *EventCrossChain) GetPackageLoad() []byte { if m != nil { return m.PackageLoad } return nil } -func (m *EventCrossChainPackage) GetRelayerFee() string { +func (m *EventCrossChain) GetRelayerFee() string { if m != nil { return m.RelayerFee } @@ -124,37 +124,36 @@ func (m *EventCrossChainPackage) GetRelayerFee() string { } func init() { - proto.RegisterType((*EventCrossChainPackage)(nil), "cosmos.crosschain.v1.EventCrossChainPackage") + proto.RegisterType((*EventCrossChain)(nil), "cosmos.crosschain.v1.EventCrossChain") } func init() { proto.RegisterFile("cosmos/crosschain/v1/event.proto", fileDescriptor_2a5a3ba75f5dd2c3) } var fileDescriptor_2a5a3ba75f5dd2c3 = []byte{ - // 323 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0x4f, 0x4e, 0xc2, 0x40, - 0x14, 0xc6, 0x19, 0x44, 0x84, 0x07, 0x6c, 0x26, 0xc6, 0x54, 0xa2, 0xb5, 0xb2, 0xea, 0xc6, 0x4e, - 0x88, 0x37, 0x90, 0x68, 0x42, 0xe2, 0xc2, 0x10, 0x57, 0x6e, 0x9a, 0x61, 0xe6, 0x09, 0x0d, 0xb4, - 0x53, 0x3b, 0x03, 0x91, 0x5b, 0x78, 0x02, 0xcf, 0xe3, 0x92, 0xa5, 0x4b, 0x03, 0x17, 0x31, 0x9d, - 0x96, 0x3f, 0xab, 0xc9, 0xfb, 0xe5, 0xf7, 0x7d, 0x79, 0x99, 0x07, 0x9e, 0x50, 0x3a, 0x56, 0x9a, - 0x89, 0x4c, 0x69, 0x2d, 0xa6, 0x3c, 0x4a, 0xd8, 0xb2, 0xcf, 0x70, 0x89, 0x89, 0x09, 0xd2, 0x4c, - 0x19, 0x45, 0xcf, 0x0b, 0x23, 0x38, 0x18, 0xc1, 0xb2, 0xdf, 0xbd, 0x2c, 0x68, 0x68, 0x1d, 0x56, - 0x2a, 0x76, 0xe8, 0x7d, 0x57, 0xe1, 0xe2, 0x31, 0x2f, 0x18, 0xe4, 0x89, 0x41, 0x9e, 0x78, 0xe1, - 0x62, 0xc6, 0x27, 0x48, 0x3d, 0x68, 0xeb, 0x4c, 0x84, 0xb6, 0x25, 0x8c, 0xa4, 0x43, 0x3c, 0xe2, - 0x77, 0x46, 0xa0, 0x33, 0x61, 0xb5, 0xa1, 0xa4, 0x3d, 0xe8, 0x48, 0xd4, 0xe6, 0xa0, 0x54, 0xad, - 0xd2, 0xca, 0xe1, 0xce, 0xb9, 0x06, 0x10, 0x53, 0x9e, 0x24, 0x38, 0xcf, 0x85, 0x13, 0x2b, 0x34, - 0x4b, 0x32, 0x94, 0xb4, 0x0b, 0x0d, 0x8d, 0x1f, 0x0b, 0x4c, 0x04, 0x3a, 0x35, 0x8f, 0xf8, 0xb5, - 0xd1, 0x7e, 0xa6, 0xb7, 0xd0, 0x4e, 0x8b, 0x5d, 0x42, 0xb3, 0x4a, 0xd1, 0x39, 0x2d, 0xda, 0x4b, - 0xf6, 0xba, 0x4a, 0x91, 0x5e, 0x41, 0xd3, 0x44, 0x31, 0x6a, 0xc3, 0xe3, 0xd4, 0xa9, 0xdb, 0xfc, - 0x01, 0x1c, 0x17, 0xcc, 0x15, 0x97, 0xce, 0x99, 0x47, 0xfc, 0xf6, 0xbe, 0xe0, 0x59, 0x71, 0x49, - 0x6f, 0xa0, 0x95, 0xe1, 0x9c, 0xaf, 0x30, 0x0b, 0xdf, 0x11, 0x9d, 0x86, 0x47, 0xfc, 0xe6, 0x08, - 0x4a, 0xf4, 0x84, 0xf8, 0x30, 0xfc, 0xd9, 0xb8, 0x64, 0xbd, 0x71, 0xc9, 0xdf, 0xc6, 0x25, 0x5f, - 0x5b, 0xb7, 0xb2, 0xde, 0xba, 0x95, 0xdf, 0xad, 0x5b, 0x79, 0x63, 0x93, 0xc8, 0x4c, 0x17, 0xe3, - 0x40, 0xa8, 0x98, 0xed, 0x0e, 0x63, 0x9f, 0x3b, 0x2d, 0x67, 0xec, 0xf3, 0xf8, 0x4a, 0xf9, 0xfa, - 0x7a, 0x5c, 0xb7, 0x5f, 0x7e, 0xff, 0x1f, 0x00, 0x00, 0xff, 0xff, 0x48, 0xe7, 0x4a, 0x77, 0xc7, - 0x01, 0x00, 0x00, + // 320 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xcd, 0x4e, 0x32, 0x31, + 0x14, 0x86, 0x29, 0x1f, 0x1f, 0xc2, 0x01, 0x62, 0xd2, 0xb8, 0x18, 0x89, 0x8e, 0x23, 0xab, 0xd9, + 0x38, 0x0d, 0xf1, 0x0e, 0x24, 0x9a, 0x90, 0xb8, 0x22, 0xae, 0xdc, 0x4c, 0x4a, 0x7b, 0x84, 0x09, + 0xcc, 0x74, 0x9c, 0x16, 0x22, 0x77, 0xe1, 0xce, 0x5b, 0x72, 0xc9, 0xd2, 0xa5, 0x81, 0x1b, 0x31, + 0x2d, 0xc3, 0xcf, 0xaa, 0x39, 0x4f, 0x9f, 0xf7, 0x4d, 0xd3, 0x03, 0x81, 0x50, 0x3a, 0x55, 0x9a, + 0x89, 0x42, 0x69, 0x2d, 0xa6, 0x3c, 0xc9, 0xd8, 0xb2, 0xcf, 0x70, 0x89, 0x99, 0x89, 0xf2, 0x42, + 0x19, 0x45, 0x2f, 0x76, 0x46, 0x74, 0x34, 0xa2, 0x65, 0xbf, 0x7b, 0xb9, 0xa3, 0xb1, 0x73, 0x58, + 0xa9, 0xb8, 0xa1, 0xf7, 0x55, 0x85, 0xf3, 0x47, 0x5b, 0x30, 0xb0, 0x89, 0x81, 0x4d, 0xd0, 0x00, + 0xda, 0xba, 0x10, 0xb1, 0x8b, 0xc7, 0x89, 0xf4, 0x48, 0x40, 0xc2, 0xce, 0x08, 0x74, 0x21, 0xdc, + 0xfd, 0x50, 0xd2, 0x1e, 0x74, 0x24, 0x6a, 0x73, 0x54, 0xaa, 0x4e, 0x69, 0x59, 0xb8, 0x77, 0xae, + 0x01, 0xc4, 0x94, 0x67, 0x19, 0xce, 0xad, 0xf0, 0xcf, 0x09, 0xcd, 0x92, 0x0c, 0x25, 0xed, 0x42, + 0x43, 0xe3, 0xfb, 0x02, 0x33, 0x81, 0x5e, 0x2d, 0x20, 0x61, 0x6d, 0x74, 0x98, 0xe9, 0x2d, 0xb4, + 0x73, 0x2e, 0x66, 0x7c, 0x82, 0xb1, 0x59, 0xe5, 0xe8, 0xfd, 0xdf, 0xb5, 0x97, 0xec, 0x65, 0x95, + 0x23, 0xbd, 0x82, 0xa6, 0x49, 0x52, 0xd4, 0x86, 0xa7, 0xb9, 0x57, 0x77, 0xf9, 0x23, 0x38, 0x2d, + 0x98, 0x2b, 0x2e, 0xbd, 0xb3, 0x80, 0x84, 0xed, 0x43, 0xc1, 0xb3, 0xe2, 0x92, 0xde, 0x40, 0xab, + 0xc0, 0x39, 0x5f, 0x61, 0x11, 0xbf, 0x21, 0x7a, 0x8d, 0x80, 0x84, 0xcd, 0x11, 0x94, 0xe8, 0x09, + 0xf1, 0x61, 0xf8, 0xbd, 0xf1, 0xc9, 0x7a, 0xe3, 0x93, 0xdf, 0x8d, 0x4f, 0x3e, 0xb7, 0x7e, 0x65, + 0xbd, 0xf5, 0x2b, 0x3f, 0x5b, 0xbf, 0xf2, 0xca, 0x26, 0x89, 0x99, 0x2e, 0xc6, 0x91, 0x50, 0x29, + 0xdb, 0x6f, 0xc4, 0x1d, 0x77, 0x5a, 0xce, 0xd8, 0xc7, 0xe9, 0x7a, 0xec, 0xf3, 0xf5, 0xb8, 0xee, + 0xfe, 0xfa, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xd1, 0x33, 0xd1, 0x2c, 0xc0, 0x01, 0x00, 0x00, } -func (m *EventCrossChainPackage) Marshal() (dAtA []byte, err error) { +func (m *EventCrossChain) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -164,12 +163,12 @@ func (m *EventCrossChainPackage) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *EventCrossChainPackage) MarshalTo(dAtA []byte) (int, error) { +func (m *EventCrossChain) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *EventCrossChainPackage) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *EventCrossChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int @@ -232,7 +231,7 @@ func encodeVarintEvent(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *EventCrossChainPackage) Size() (n int) { +func (m *EventCrossChain) Size() (n int) { if m == nil { return 0 } @@ -273,7 +272,7 @@ func sovEvent(x uint64) (n int) { func sozEvent(x uint64) (n int) { return sovEvent(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } -func (m *EventCrossChainPackage) Unmarshal(dAtA []byte) error { +func (m *EventCrossChain) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -296,10 +295,10 @@ func (m *EventCrossChainPackage) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: EventCrossChainPackage: wiretype end group for non-group") + return fmt.Errorf("proto: EventCrossChain: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: EventCrossChainPackage: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: EventCrossChain: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 62fb9903ff..150ca35fc7 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -2,12 +2,13 @@ package types import ( "fmt" + "math/big" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) const ( - DefaultRelayerFeeParam uint64 = 1e6 // decimal is 8 + DefaultRelayerFeeParam string = "100000000" // TODO: tbd ) var ( @@ -32,13 +33,20 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { } func validateRelayerFee(i interface{}) error { - v, ok := i.(uint64) + v, ok := i.(string) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } - if v <= 0 { - return fmt.Errorf("the syn_package_fee must be positive: %d", v) + relayerFee := big.NewInt(0) + relayerFee, valid := relayerFee.SetString(v, 10) + + if !valid { + return fmt.Errorf("invalid relayer fee, %s", v) + } + + if relayerFee.Cmp(big.NewInt(0)) < 0 { + return fmt.Errorf("invalid relayer fee, %s", v) } return nil diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index a63f56fdb9..798449ee12 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -3,8 +3,6 @@ package keeper import ( "fmt" - crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" - sdkerrors "cosmossdk.io/errors" "github.com/prysmaticlabs/prysm/crypto/bls" "github.com/willf/bitset" @@ -12,6 +10,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" "github.com/cosmos/cosmos-sdk/x/oracle/metrics" "github.com/cosmos/cosmos-sdk/x/oracle/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" From d0b11ea0ab713fec031912e09737c763f0833c3f Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 6 Dec 2022 19:17:53 +0800 Subject: [PATCH 12/50] add smartchain address --- bsc/address.go | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++ types/hex.go | 52 ++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 bsc/address.go create mode 100644 types/hex.go diff --git a/bsc/address.go b/bsc/address.go new file mode 100644 index 0000000000..ee45d5eba9 --- /dev/null +++ b/bsc/address.go @@ -0,0 +1,71 @@ +package bsc + +import ( + "encoding/hex" + "fmt" + "math/big" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" +) + +const ( + // SmartChainAddressLength defines a valid smart chain address length + SmartChainAddressLength = 20 +) + +// SmartChainAddress defines a standard smart chain address +type SmartChainAddress [SmartChainAddressLength]byte + +// NewSmartChainAddress is a constructor function for SmartChainAddress +func NewSmartChainAddress(addr string) (SmartChainAddress, error) { + addr = strings.ToLower(addr) + if len(addr) >= 2 && addr[:2] == "0x" { + addr = addr[2:] + } + if length := len(addr); length != 2*SmartChainAddressLength { + return SmartChainAddress{}, fmt.Errorf("invalid address hex length: %v != %v", length, 2*SmartChainAddressLength) + } + + bin, err := hex.DecodeString(addr) + if err != nil { + return SmartChainAddress{}, err + } + var address SmartChainAddress + address.SetBytes(bin) + return address, nil +} + +func (addr *SmartChainAddress) SetBytes(b []byte) { + if len(b) > len(addr) { + b = b[len(b)-20:] + } + copy(addr[20-len(b):], b) +} + +func (addr SmartChainAddress) IsEmpty() bool { + addrValue := big.NewInt(0) + addrValue.SetBytes(addr[:]) + + return addrValue.Cmp(big.NewInt(0)) == 0 +} + +// Route should return the name of the module +func (addr SmartChainAddress) String() string { + return sdk.HexAddress(addr[:]) +} + +// MarshalJSON marshals the smart chain address to JSON +func (addr SmartChainAddress) MarshalJSON() ([]byte, error) { + return []byte(fmt.Sprintf("\"%v\"", addr.String())), nil +} + +// UnmarshalJSON unmarshals an smart chain address +func (addr *SmartChainAddress) UnmarshalJSON(input []byte) error { + hexBytes, err := sdk.HexDecode(string(input[1 : len(input)-1])) + if err != nil { + return err + } + addr.SetBytes(hexBytes) + return nil +} diff --git a/types/hex.go b/types/hex.go new file mode 100644 index 0000000000..fe8c0fe859 --- /dev/null +++ b/types/hex.go @@ -0,0 +1,52 @@ +package types + +import ( + "encoding/hex" + "errors" + + "golang.org/x/crypto/sha3" +) + +func HexAddress(a []byte) string { + if len(a) == 0 { + return "" + } + unchecksummed := hex.EncodeToString(a[:]) + sha := sha3.NewLegacyKeccak256() + sha.Write([]byte(unchecksummed)) + hash := sha.Sum(nil) + + result := []byte(unchecksummed) + for i := 0; i < len(result); i++ { + hashByte := hash[i/2] + if i%2 == 0 { + hashByte = hashByte >> 4 + } else { + hashByte &= 0xf + } + if result[i] > '9' && hashByte > 7 { + result[i] -= 32 + } + } + return "0x" + string(result) +} + +func HexEncode(b []byte) string { + enc := make([]byte, len(b)*2+2) + copy(enc, "0x") + hex.Encode(enc[2:], b) + return string(enc) +} + +// Decode decodes a hex string with 0x prefix. +func HexDecode(input string) ([]byte, error) { + if !Has0xPrefix(input) { + return nil, errors.New("hex string must have 0x prefix") + } + return hex.DecodeString(input[2:]) +} + +// has0xPrefix validates str begins with '0x' or '0X'. +func Has0xPrefix(input string) bool { + return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') +} From d76c18fb55590e2eb78438260fde25dea6c95b84 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 16 Dec 2022 15:45:51 +0800 Subject: [PATCH 13/50] update hash algo of bls sig --- types/hex.go | 21 +++++++++++++++++++++ types/hex_test.go | 14 ++++++++++++++ x/oracle/types/msgs.go | 3 +-- 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 types/hex_test.go diff --git a/types/hex.go b/types/hex.go index fe8c0fe859..f460f7a922 100644 --- a/types/hex.go +++ b/types/hex.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "errors" + "github.com/ethereum/go-ethereum/common" "golang.org/x/crypto/sha3" ) @@ -50,3 +51,23 @@ func HexDecode(input string) ([]byte, error) { func Has0xPrefix(input string) bool { return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') } + +// Keccak256 calculates and returns the Keccak256 hash of the input data. +func Keccak256(data ...[]byte) []byte { + d := sha3.NewLegacyKeccak256() + for _, b := range data { + d.Write(b) + } + return d.Sum(nil) +} + +// Keccak256Hash calculates and returns the Keccak256 hash of the input data, +// converting it to an internal Hash data structure. +func Keccak256Hash(data ...[]byte) (h common.Hash) { + d := sha3.NewLegacyKeccak256() + for _, b := range data { + d.Write(b) + } + d.Sum(h[:0]) + return h +} diff --git a/types/hex_test.go b/types/hex_test.go new file mode 100644 index 0000000000..ffa93c008e --- /dev/null +++ b/types/hex_test.go @@ -0,0 +1,14 @@ +package types + +import ( + "encoding/hex" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestKeccak256Hash(t *testing.T) { + input := []byte("test input") + hash := Keccak256Hash(input) + require.Equal(t, "1df1102036c102fbc689e6f72a64a9162ae0b1ea151932530deb8cd186c36c01", hex.EncodeToString(hash[:])) +} diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 9d21026cdd..c50a715fec 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -7,7 +7,6 @@ import ( "github.com/cosmos/cosmos-sdk/bsc/rlp" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/prysmaticlabs/prysm/crypto/hash" ) const ( @@ -95,7 +94,7 @@ func (c *BlsClaim) GetSignBytes() [32]byte { panic("encode bls claim error") } - btsHash := hash.Hash(bts) + btsHash := sdk.Keccak256Hash(bts) return btsHash } From 66382692876bd92f252df5deb47cde72adbd7a07 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 19 Dec 2022 15:15:35 +0800 Subject: [PATCH 14/50] update module name --- x/oracle/module.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/oracle/module.go b/x/oracle/module.go index 99be572dad..12dc7bede3 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -1,4 +1,4 @@ -package crosschain +package oracle import ( "encoding/json" From c1a1e3649209d93eeb93279d632a34ce5c3eeb24 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 19 Dec 2022 18:40:45 +0800 Subject: [PATCH 15/50] fix package name --- proto/cosmos/oracle/v1/query.proto | 2 +- x/oracle/types/msgs.go | 12 ++++++++++++ x/oracle/types/query.pb.go | 23 +++++++++++------------ 3 files changed, 24 insertions(+), 13 deletions(-) diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto index 0da5f8ca38..1915d0295d 100644 --- a/proto/cosmos/oracle/v1/query.proto +++ b/proto/cosmos/oracle/v1/query.proto @@ -1,5 +1,5 @@ syntax = "proto3"; -package cosmos.crosschain.v1; +package cosmos.oracle.v1; import "gogoproto/gogo.proto"; import "google/api/annotations.proto"; diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index c50a715fec..a3d89dff7f 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -18,6 +18,18 @@ const ( type BLSPublicKey [BLSPublicKeyLength]byte type BLSSignature [BLSSignatureLength]byte +func NewMsgClaim(fromAddr string, chainId uint32, sequence uint64, timestamp uint64, payload []byte, voteAddrSet []uint64, aggSignature []byte) *MsgClaim { + return &MsgClaim{ + FromAddress: fromAddr, + ChainId: chainId, + Sequence: sequence, + Timestamp: timestamp, + Payload: payload, + VoteAddressSet: voteAddrSet, + AggSignature: aggSignature, + } +} + // Route implements the LegacyMsg interface. func (m MsgClaim) Route() string { return sdk.MsgTypeURL(&m) } diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index 2698b26b52..82b8058075 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -28,19 +28,18 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func init() { proto.RegisterFile("cosmos/oracle/v1/query.proto", fileDescriptor_9f804c4644f3aaef) } var fileDescriptor_9f804c4644f3aaef = []byte{ - // 180 bytes of a gzipped FileDescriptorProto + // 172 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, - 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xc8, 0xea, 0x25, 0x17, 0xe5, - 0x17, 0x17, 0x27, 0x67, 0x24, 0x66, 0xe6, 0xe9, 0x95, 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, - 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x32, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0xfa, - 0x89, 0x05, 0x99, 0xfa, 0x89, 0x79, 0x79, 0xf9, 0x25, 0x89, 0x25, 0x99, 0xf9, 0x79, 0xc5, 0x10, - 0x59, 0x23, 0x76, 0x2e, 0xd6, 0x40, 0x90, 0xc1, 0x4e, 0xae, 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, 0x9d, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, - 0x0f, 0x75, 0x15, 0x84, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, 0x80, 0x39, 0xb1, 0xa4, 0xb2, 0x20, - 0xb5, 0x38, 0x89, 0x0d, 0x6c, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0xa0, 0xa2, 0x54, 0xe6, - 0xc0, 0x00, 0x00, 0x00, + 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x80, 0xc8, 0xea, 0x41, 0x64, 0xf5, + 0xca, 0x0c, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x92, 0xfa, 0x20, 0x16, 0x44, 0x9d, 0x94, + 0x4c, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x7e, 0x62, 0x41, 0xa6, 0x7e, 0x62, 0x5e, 0x5e, 0x7e, + 0x49, 0x62, 0x49, 0x66, 0x7e, 0x5e, 0x31, 0x44, 0xd6, 0x88, 0x9d, 0x8b, 0x35, 0x10, 0x64, 0xa8, + 0x93, 0xeb, 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, 0xa7, 0x67, 0x96, + 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x5d, 0x04, 0xa1, 0x74, 0x8b, 0x53, 0xb2, + 0xf5, 0x2b, 0x60, 0xce, 0x2b, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x1b, 0x6b, 0x0c, 0x08, + 0x00, 0x00, 0xff, 0xff, 0xb5, 0xe1, 0x17, 0x67, 0xbc, 0x00, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -78,7 +77,7 @@ func RegisterQueryServer(s grpc1.Server, srv QueryServer) { } var _Query_serviceDesc = grpc.ServiceDesc{ - ServiceName: "cosmos.crosschain.v1.Query", + ServiceName: "cosmos.oracle.v1.Query", HandlerType: (*QueryServer)(nil), Methods: []grpc.MethodDesc{}, Streams: []grpc.StreamDesc{}, From e7392e90003142aa094042d726021bc2f4813be3 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 19 Dec 2022 19:55:03 +0800 Subject: [PATCH 16/50] delete bech32 address --- bsc/address.go | 71 ------------------------------------------ x/oracle/types/msgs.go | 4 +-- 2 files changed, 2 insertions(+), 73 deletions(-) delete mode 100644 bsc/address.go diff --git a/bsc/address.go b/bsc/address.go deleted file mode 100644 index ee45d5eba9..0000000000 --- a/bsc/address.go +++ /dev/null @@ -1,71 +0,0 @@ -package bsc - -import ( - "encoding/hex" - "fmt" - "math/big" - "strings" - - sdk "github.com/cosmos/cosmos-sdk/types" -) - -const ( - // SmartChainAddressLength defines a valid smart chain address length - SmartChainAddressLength = 20 -) - -// SmartChainAddress defines a standard smart chain address -type SmartChainAddress [SmartChainAddressLength]byte - -// NewSmartChainAddress is a constructor function for SmartChainAddress -func NewSmartChainAddress(addr string) (SmartChainAddress, error) { - addr = strings.ToLower(addr) - if len(addr) >= 2 && addr[:2] == "0x" { - addr = addr[2:] - } - if length := len(addr); length != 2*SmartChainAddressLength { - return SmartChainAddress{}, fmt.Errorf("invalid address hex length: %v != %v", length, 2*SmartChainAddressLength) - } - - bin, err := hex.DecodeString(addr) - if err != nil { - return SmartChainAddress{}, err - } - var address SmartChainAddress - address.SetBytes(bin) - return address, nil -} - -func (addr *SmartChainAddress) SetBytes(b []byte) { - if len(b) > len(addr) { - b = b[len(b)-20:] - } - copy(addr[20-len(b):], b) -} - -func (addr SmartChainAddress) IsEmpty() bool { - addrValue := big.NewInt(0) - addrValue.SetBytes(addr[:]) - - return addrValue.Cmp(big.NewInt(0)) == 0 -} - -// Route should return the name of the module -func (addr SmartChainAddress) String() string { - return sdk.HexAddress(addr[:]) -} - -// MarshalJSON marshals the smart chain address to JSON -func (addr SmartChainAddress) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("\"%v\"", addr.String())), nil -} - -// UnmarshalJSON unmarshals an smart chain address -func (addr *SmartChainAddress) UnmarshalJSON(input []byte) error { - hexBytes, err := sdk.HexDecode(string(input[1 : len(input)-1])) - if err != nil { - return err - } - addr.SetBytes(hexBytes) - return nil -} diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index a3d89dff7f..96c2375e7b 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -43,7 +43,7 @@ func (m MsgClaim) GetSignBytes() []byte { // ValidateBasic does a sanity check on the provided data. func (m *MsgClaim) ValidateBasic() error { - if _, err := sdk.AccAddressFromBech32(m.FromAddress); err != nil { + if _, err := sdk.AccAddressFromHexUnsafe(m.FromAddress); err != nil { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) } @@ -78,7 +78,7 @@ func (m *MsgClaim) ValidateBasic() error { // GetSigners returns the expected signers for MsgCancelUpgrade. func (m *MsgClaim) GetSigners() []sdk.AccAddress { - fromAddress, _ := sdk.AccAddressFromBech32(m.FromAddress) + fromAddress := sdk.MustAccAddressFromHex(m.FromAddress) return []sdk.AccAddress{fromAddress} } From 433863ac867464dd2d38c635d938c16cde3fc6fe Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 20 Dec 2022 15:11:03 +0800 Subject: [PATCH 17/50] register oracle msg server --- x/oracle/keeper/msg_server.go | 8 +++----- x/oracle/module.go | 1 + 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 033001534c..63ac24c484 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -15,16 +15,14 @@ import ( ) type msgServer struct { - oracleKeeper Keeper - stakingKeeper types.StakingKeeper + oracleKeeper Keeper } // NewMsgServerImpl returns an implementation of the oracle MsgServer interface // for the provided Keeper. -func NewMsgServerImpl(k Keeper, stakingKeeper types.StakingKeeper) types.MsgServer { +func NewMsgServerImpl(k Keeper) types.MsgServer { return &msgServer{ - oracleKeeper: k, - stakingKeeper: stakingKeeper, + oracleKeeper: k, } } diff --git a/x/oracle/module.go b/x/oracle/module.go index 12dc7bede3..55443315f7 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -101,6 +101,7 @@ func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sd // RegisterServices registers a gRPC query service to respond to the // module-specific gRPC queries. func (am AppModule) RegisterServices(cfg module.Configurator) { + types.RegisterMsgServer(cfg.MsgServer(), keeper.NewMsgServerImpl(am.keeper)) types.RegisterQueryServer(cfg.QueryServer(), am.keeper) } From 0c54924c89e26b59baacdea78cb6a60210cb8047 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 20 Dec 2022 15:24:34 +0800 Subject: [PATCH 18/50] register msgs --- x/oracle/module.go | 8 ++++++-- x/oracle/types/codec.go | 25 ++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/x/oracle/module.go b/x/oracle/module.go index 55443315f7..a34e6d4531 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -34,7 +34,9 @@ func (AppModuleBasic) Name() string { } // RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. -func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} +func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + types.RegisterCodec(cdc) +} // DefaultGenesis returns default genesis state as raw bytes for the params // module. @@ -58,7 +60,9 @@ func (AppModuleBasic) GetQueryCmd() *cobra.Command { return cli.NewQueryCmd() } -func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) {} +func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) +} // AppModule implements an application module for the distribution module. type AppModule struct { diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go index 956b536831..33d0a6da80 100644 --- a/x/oracle/types/codec.go +++ b/x/oracle/types/codec.go @@ -1,8 +1,27 @@ package types -import "github.com/cosmos/cosmos-sdk/codec" +import ( + "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/msgservice" +) + +func RegisterCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgClaim{}, "oracle/Claim", nil) + // this line is used by starport scaffolding # 2 +} + +func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgClaim{}, + ) + // this line is used by starport scaffolding # 3 + + msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) +} var ( - amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewAminoCodec(amino) + Amino = codec.NewLegacyAmino() + ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) ) From 9bc618e0605c6cc7e19aa5e1cf6cca66e241c64e Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 26 Dec 2022 15:10:30 +0800 Subject: [PATCH 19/50] init codec --- x/oracle/types/codec.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go index 33d0a6da80..5408eba846 100644 --- a/x/oracle/types/codec.go +++ b/x/oracle/types/codec.go @@ -23,5 +23,9 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { var ( Amino = codec.NewLegacyAmino() - ModuleCdc = codec.NewProtoCodec(cdctypes.NewInterfaceRegistry()) + ModuleCdc = codec.NewAminoCodec(Amino) ) + +func init() { + RegisterCodec(Amino) +} From 5983dd2d245a4d65a123284c8c20a48ee2c8ac06 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 27 Dec 2022 14:38:27 +0800 Subject: [PATCH 20/50] update codec --- x/oracle/module.go | 2 +- x/oracle/types/codec.go | 17 ++++++++++++++--- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/x/oracle/module.go b/x/oracle/module.go index a34e6d4531..06d50346a3 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -35,7 +35,7 @@ func (AppModuleBasic) Name() string { // RegisterLegacyAminoCodec registers the params module's types on the given LegacyAmino codec. func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { - types.RegisterCodec(cdc) + types.RegisterLegacyAminoCodec(cdc) } // DefaultGenesis returns default genesis state as raw bytes for the params diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go index 5408eba846..39b5283ff6 100644 --- a/x/oracle/types/codec.go +++ b/x/oracle/types/codec.go @@ -3,12 +3,17 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + authzcodec "github.com/cosmos/cosmos-sdk/x/authz/codec" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/msgservice" ) -func RegisterCodec(cdc *codec.LegacyAmino) { - cdc.RegisterConcrete(&MsgClaim{}, "oracle/Claim", nil) +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { + cdc.RegisterConcrete(&MsgClaim{}, "cosmos-sdk/MsgClaim", nil) + + //legacy.RegisterAminoMsg(cdc, &MsgClaim{}, "cosmos-sdk/MsgClaim") // this line is used by starport scaffolding # 2 } @@ -27,5 +32,11 @@ var ( ) func init() { - RegisterCodec(Amino) + RegisterLegacyAminoCodec(Amino) + cryptocodec.RegisterCrypto(Amino) + sdk.RegisterLegacyAminoCodec(Amino) + + // Register all Amino interfaces and concrete types on the authz Amino codec so that this can later be + // used to properly serialize MsgGrant and MsgExec instances + RegisterLegacyAminoCodec(authzcodec.Amino) } From 31b30f1a1c99b263a045e0238321a094dda611cb Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 28 Dec 2022 09:15:04 +0800 Subject: [PATCH 21/50] update msg claim --- proto/cosmos/oracle/v1/tx.proto | 13 +-- x/oracle/keeper/msg_server.go | 11 ++- x/oracle/types/errors.go | 1 + x/oracle/types/expected_keepers.go | 1 + x/oracle/types/msgs.go | 30 ++++--- x/oracle/types/tx.pb.go | 125 ++++++++++++++++++----------- 6 files changed, 113 insertions(+), 68 deletions(-) diff --git a/proto/cosmos/oracle/v1/tx.proto b/proto/cosmos/oracle/v1/tx.proto index e4f9da65ea..34a4ac008f 100644 --- a/proto/cosmos/oracle/v1/tx.proto +++ b/proto/cosmos/oracle/v1/tx.proto @@ -21,12 +21,13 @@ message MsgClaim { option (gogoproto.goproto_getters) = false; string from_address = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"]; - uint32 chain_id = 2; - uint64 sequence = 3; - uint64 timestamp = 4; - bytes payload = 5; - repeated fixed64 vote_address_set = 6; - bytes agg_signature = 7; + uint32 src_chain_id = 2; + uint32 dest_chain_id = 3; + uint64 sequence = 4; + uint64 timestamp = 5; + bytes payload = 6; + repeated fixed64 vote_address_set = 7; + bytes agg_signature = 8; } // MsgClaimResponse defines the Msg/Claim response type diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 63ac24c484..0d0d520ac6 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -31,7 +31,12 @@ var _ types.MsgServer = msgServer{} func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.MsgClaimResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) - sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, sdk.ChainID(req.ChainId), types.RelayPackagesChannelId) + // check dest chain id + if sdk.ChainID(req.DestChainId) != k.oracleKeeper.CrossChainKeeper.GetSrcChainID() { + return nil, sdkerrors.Wrapf(types.ErrInvalidDestChainId, fmt.Sprintf("dest chain id(%d) should be %d", req.SrcChainId, k.oracleKeeper.CrossChainKeeper.GetSrcChainID())) + } + + sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), types.RelayPackagesChannelId) if sequence != req.Sequence { return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", types.RelayPackagesChannelId, sequence)) } @@ -49,7 +54,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg events := make([]proto.Message, 0, len(packages)) for _, pack := range packages { - event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.ChainId), &pack) + event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) if err != nil { // only do log, but let reset package get chance to execute. ctx.Logger().With("module", "oracle").Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) @@ -60,7 +65,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg events = append(events, event) // increase channel sequence - k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, sdk.ChainID(req.ChainId), pack.ChannelId) + k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), pack.ChannelId) } ctx.EventManager().EmitTypedEvents(events...) diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index 552c0ba0fa..bd2005a431 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -16,4 +16,5 @@ var ( ErrInvalidBlsSignature = sdkerrors.Register(ModuleName, 11, "bls signature is invalid") ErrNotValidator = sdkerrors.Register(ModuleName, 12, "sender is not validator") ErrValidatorNotInTurn = sdkerrors.Register(ModuleName, 13, "validator is not in turn") + ErrInvalidDestChainId = sdkerrors.Register(ModuleName, 14, "dest chain id is invalid") ) diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index f51ef290a4..883bf0933d 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -13,6 +13,7 @@ type CrossChainKeeper interface { CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication + GetSrcChainID() sdk.ChainID GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) } diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index 96c2375e7b..c93b442bfa 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -18,10 +18,11 @@ const ( type BLSPublicKey [BLSPublicKeyLength]byte type BLSSignature [BLSSignatureLength]byte -func NewMsgClaim(fromAddr string, chainId uint32, sequence uint64, timestamp uint64, payload []byte, voteAddrSet []uint64, aggSignature []byte) *MsgClaim { +func NewMsgClaim(fromAddr string, srcShainId, destChainId uint32, sequence uint64, timestamp uint64, payload []byte, voteAddrSet []uint64, aggSignature []byte) *MsgClaim { return &MsgClaim{ FromAddress: fromAddr, - ChainId: chainId, + SrcChainId: srcShainId, + DestChainId: destChainId, Sequence: sequence, Timestamp: timestamp, Payload: payload, @@ -47,7 +48,12 @@ func (m *MsgClaim) ValidateBasic() error { return sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err) } - if m.ChainId > math.MaxUint16 { + if m.SrcChainId > math.MaxUint16 { + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, + fmt.Sprintf("chain id should not be larger than %d", math.MaxUint16)) + } + + if m.DestChainId > math.MaxUint16 { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("chain id should not be larger than %d", math.MaxUint16)) } @@ -85,19 +91,21 @@ func (m *MsgClaim) GetSigners() []sdk.AccAddress { // GetBlsSignBytes returns the sign bytes of bls signature func (m *MsgClaim) GetBlsSignBytes() [32]byte { blsClaim := &BlsClaim{ - ChainId: m.ChainId, - Timestamp: m.Timestamp, - Sequence: m.Sequence, - Payload: m.Payload, + SrcChainId: m.SrcChainId, + DestChainId: m.DestChainId, + Timestamp: m.Timestamp, + Sequence: m.Sequence, + Payload: m.Payload, } return blsClaim.GetSignBytes() } type BlsClaim struct { - ChainId uint32 - Timestamp uint64 - Sequence uint64 - Payload []byte + SrcChainId uint32 + DestChainId uint32 + Timestamp uint64 + Sequence uint64 + Payload []byte } func (c *BlsClaim) GetSignBytes() [32]byte { diff --git a/x/oracle/types/tx.pb.go b/x/oracle/types/tx.pb.go index 6a114d42e7..2db62ec887 100644 --- a/x/oracle/types/tx.pb.go +++ b/x/oracle/types/tx.pb.go @@ -34,12 +34,13 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // MsgClaim defines the Msg/Claim request type type MsgClaim struct { FromAddress string `protobuf:"bytes,1,opt,name=from_address,json=fromAddress,proto3" json:"from_address,omitempty"` - ChainId uint32 `protobuf:"varint,2,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - Sequence uint64 `protobuf:"varint,3,opt,name=sequence,proto3" json:"sequence,omitempty"` - Timestamp uint64 `protobuf:"varint,4,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - Payload []byte `protobuf:"bytes,5,opt,name=payload,proto3" json:"payload,omitempty"` - VoteAddressSet []uint64 `protobuf:"fixed64,6,rep,packed,name=vote_address_set,json=voteAddressSet,proto3" json:"vote_address_set,omitempty"` - AggSignature []byte `protobuf:"bytes,7,opt,name=agg_signature,json=aggSignature,proto3" json:"agg_signature,omitempty"` + SrcChainId uint32 `protobuf:"varint,2,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` + DestChainId uint32 `protobuf:"varint,3,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` + Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` + Timestamp uint64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + Payload []byte `protobuf:"bytes,6,opt,name=payload,proto3" json:"payload,omitempty"` + VoteAddressSet []uint64 `protobuf:"fixed64,7,rep,packed,name=vote_address_set,json=voteAddressSet,proto3" json:"vote_address_set,omitempty"` + AggSignature []byte `protobuf:"bytes,8,opt,name=agg_signature,json=aggSignature,proto3" json:"agg_signature,omitempty"` } func (m *MsgClaim) Reset() { *m = MsgClaim{} } @@ -120,33 +121,34 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/tx.proto", fileDescriptor_836933fb4b988e66) } var fileDescriptor_836933fb4b988e66 = []byte{ - // 410 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x31, 0x6f, 0xd3, 0x40, - 0x14, 0xc7, 0x7d, 0x4d, 0x9b, 0xa4, 0x47, 0x8a, 0xa2, 0x53, 0x25, 0x2e, 0x16, 0x72, 0xad, 0xb0, - 0x58, 0xa0, 0xda, 0x2a, 0x6c, 0x30, 0x51, 0x06, 0xd4, 0xa1, 0x0c, 0xee, 0xc6, 0x62, 0x5d, 0xec, - 0xe3, 0x62, 0x91, 0xf3, 0x19, 0xbf, 0x4b, 0x94, 0xac, 0x4c, 0x8c, 0x7c, 0x84, 0x8c, 0x8c, 0x0c, - 0x7c, 0x08, 0xc6, 0x88, 0x89, 0x11, 0x39, 0x03, 0x7c, 0x0c, 0x64, 0x9f, 0x0f, 0x04, 0x52, 0x27, - 0xfb, 0xfd, 0x7f, 0xef, 0xfd, 0xf5, 0xf4, 0xfe, 0x87, 0x27, 0xa9, 0x02, 0xa9, 0x20, 0x52, 0x15, - 0x4b, 0x17, 0x3c, 0x5a, 0x5d, 0x44, 0x7a, 0x1d, 0x96, 0x95, 0xd2, 0x8a, 0x8c, 0x0d, 0x0a, 0x0d, - 0x0a, 0x57, 0x17, 0xee, 0xa9, 0x50, 0x42, 0xb5, 0x30, 0x6a, 0xfe, 0x4c, 0x9f, 0xdb, 0x59, 0x24, - 0x06, 0x74, 0x43, 0x06, 0xdd, 0xeb, 0xdc, 0x25, 0x88, 0xc6, 0x5a, 0x82, 0x30, 0x60, 0xba, 0x3d, - 0xc0, 0xc3, 0x6b, 0x10, 0x2f, 0x16, 0x2c, 0x97, 0xe4, 0x19, 0x1e, 0xbd, 0xa9, 0x94, 0x4c, 0x58, - 0x96, 0x55, 0x1c, 0x80, 0x22, 0x1f, 0x05, 0xc7, 0x97, 0xf4, 0xdb, 0x97, 0xf3, 0xd3, 0xce, 0xed, - 0xb9, 0x21, 0x37, 0xba, 0xca, 0x0b, 0x11, 0xdf, 0x69, 0xba, 0x3b, 0x89, 0x4c, 0xf0, 0x30, 0x9d, - 0xb3, 0xbc, 0x48, 0xf2, 0x8c, 0x1e, 0xf8, 0x28, 0x38, 0x89, 0x07, 0x6d, 0x7d, 0x95, 0x11, 0x17, - 0x0f, 0x81, 0xbf, 0x5b, 0xf2, 0x22, 0xe5, 0xb4, 0xe7, 0xa3, 0xe0, 0x30, 0xfe, 0x53, 0x93, 0xfb, - 0xf8, 0x58, 0xe7, 0x92, 0x83, 0x66, 0xb2, 0xa4, 0x87, 0x2d, 0xfc, 0x2b, 0x10, 0x8a, 0x07, 0x25, - 0xdb, 0x2c, 0x14, 0xcb, 0xe8, 0x91, 0x8f, 0x82, 0x51, 0x6c, 0x4b, 0x12, 0xe0, 0xf1, 0x4a, 0x69, - 0x6e, 0x77, 0x4d, 0x80, 0x6b, 0xda, 0xf7, 0x7b, 0x41, 0x3f, 0xbe, 0xdb, 0xe8, 0x76, 0x51, 0xae, - 0xc9, 0x03, 0x7c, 0xc2, 0x84, 0x48, 0x20, 0x17, 0x05, 0xd3, 0xcb, 0x8a, 0xd3, 0x41, 0xeb, 0x34, - 0x62, 0x42, 0xdc, 0x58, 0xed, 0xe9, 0xe4, 0xc3, 0xf6, 0xcc, 0xf9, 0xb5, 0x3d, 0x73, 0xde, 0xff, - 0xfc, 0xfc, 0xf0, 0x9f, 0x2b, 0x4c, 0x09, 0x1e, 0xdb, 0x0b, 0xc5, 0x1c, 0x4a, 0x55, 0x00, 0x7f, - 0xfc, 0x0a, 0xf7, 0xae, 0x41, 0x90, 0x97, 0xf8, 0xc8, 0x5c, 0xce, 0x0d, 0xff, 0xcf, 0x28, 0xb4, - 0x33, 0xee, 0xf4, 0x76, 0x66, 0xfd, 0x2e, 0xaf, 0x3e, 0xd5, 0x1e, 0xfa, 0x5a, 0x7b, 0x68, 0x57, - 0x7b, 0xe8, 0x47, 0xed, 0xa1, 0x8f, 0x7b, 0xcf, 0xd9, 0xed, 0x3d, 0xe7, 0xfb, 0xde, 0x73, 0x5e, - 0x3f, 0x12, 0xb9, 0x9e, 0x2f, 0x67, 0x61, 0xaa, 0x64, 0x17, 0x6b, 0xf7, 0x39, 0x87, 0xec, 0x6d, - 0xb4, 0xb6, 0x6f, 0x46, 0x6f, 0x4a, 0x0e, 0xb3, 0x7e, 0x1b, 0xec, 0x93, 0xdf, 0x01, 0x00, 0x00, - 0xff, 0xff, 0xb4, 0x46, 0xec, 0xf2, 0x51, 0x02, 0x00, 0x00, + // 430 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x31, 0x6f, 0xd4, 0x30, + 0x14, 0xc7, 0xe3, 0x5e, 0x7b, 0xbd, 0xba, 0x77, 0xe8, 0x64, 0x55, 0xc2, 0x8d, 0x50, 0x1a, 0x1d, + 0x4b, 0x04, 0x6a, 0xa2, 0xc2, 0x06, 0x13, 0xed, 0x80, 0x3a, 0x94, 0x21, 0xdd, 0x58, 0x22, 0x37, + 0x31, 0x6e, 0xc4, 0x39, 0x0e, 0x7e, 0xbe, 0x53, 0xbb, 0x32, 0x31, 0xf2, 0x11, 0x3a, 0x32, 0x32, + 0xf0, 0x21, 0x90, 0x58, 0x2a, 0x26, 0x46, 0x94, 0x1b, 0xe0, 0x63, 0xa0, 0xc4, 0x31, 0x27, 0x90, + 0x3a, 0x25, 0xef, 0xff, 0xfb, 0xbf, 0xbf, 0xf4, 0x9e, 0x1f, 0xde, 0xcf, 0x15, 0x48, 0x05, 0x89, + 0xd2, 0x2c, 0x9f, 0xf3, 0x64, 0x79, 0x94, 0x98, 0xab, 0xb8, 0xd6, 0xca, 0x28, 0x32, 0xb5, 0x28, + 0xb6, 0x28, 0x5e, 0x1e, 0xf9, 0x7b, 0x42, 0x09, 0xd5, 0xc1, 0xa4, 0xfd, 0xb3, 0x3e, 0xbf, 0x8f, + 0xc8, 0x2c, 0xe8, 0x9b, 0x2c, 0xba, 0xdf, 0xa7, 0x4b, 0x10, 0x6d, 0xb4, 0x04, 0x61, 0xc1, 0xec, + 0xdb, 0x06, 0x1e, 0x9d, 0x81, 0x38, 0x99, 0xb3, 0x52, 0x92, 0xe7, 0x78, 0xfc, 0x46, 0x2b, 0x99, + 0xb1, 0xa2, 0xd0, 0x1c, 0x80, 0xa2, 0x10, 0x45, 0x3b, 0xc7, 0xf4, 0xfb, 0x97, 0xc3, 0xbd, 0x3e, + 0xed, 0x85, 0x25, 0xe7, 0x46, 0x97, 0x95, 0x48, 0x77, 0x5b, 0x77, 0x2f, 0x91, 0x10, 0x8f, 0x41, + 0xe7, 0x59, 0x7e, 0xc9, 0xca, 0x2a, 0x2b, 0x0b, 0xba, 0x11, 0xa2, 0x68, 0x92, 0x62, 0xd0, 0xf9, + 0x49, 0x2b, 0x9d, 0x16, 0x64, 0x86, 0x27, 0x05, 0x07, 0xb3, 0xb6, 0x0c, 0x3a, 0xcb, 0x6e, 0x2b, + 0x3a, 0x8f, 0x8f, 0x47, 0xc0, 0xdf, 0x2d, 0x78, 0x95, 0x73, 0xba, 0x19, 0xa2, 0x68, 0x33, 0xfd, + 0x5b, 0x93, 0x07, 0x78, 0xc7, 0x94, 0x92, 0x83, 0x61, 0xb2, 0xa6, 0x5b, 0x1d, 0x5c, 0x0b, 0x84, + 0xe2, 0xed, 0x9a, 0x5d, 0xcf, 0x15, 0x2b, 0xe8, 0x30, 0x44, 0xd1, 0x38, 0x75, 0x25, 0x89, 0xf0, + 0x74, 0xa9, 0x0c, 0x77, 0x63, 0x65, 0xc0, 0x0d, 0xdd, 0x0e, 0x07, 0xd1, 0x30, 0xbd, 0xd7, 0xea, + 0x6e, 0x26, 0x6e, 0xc8, 0x43, 0x3c, 0x61, 0x42, 0x64, 0x50, 0x8a, 0x8a, 0x99, 0x85, 0xe6, 0x74, + 0xd4, 0x25, 0x8d, 0x99, 0x10, 0xe7, 0x4e, 0x7b, 0xb6, 0xff, 0xe1, 0xe6, 0xc0, 0xfb, 0x7d, 0x73, + 0xe0, 0xbd, 0xff, 0xf5, 0xf9, 0xd1, 0x3f, 0x0b, 0x9b, 0x11, 0x3c, 0x75, 0xcb, 0x4c, 0x39, 0xd4, + 0xaa, 0x02, 0xfe, 0xe4, 0x15, 0x1e, 0x9c, 0x81, 0x20, 0x2f, 0xf1, 0x96, 0x5d, 0xb2, 0x1f, 0xff, + 0xff, 0x9c, 0xb1, 0xeb, 0xf1, 0x67, 0x77, 0x33, 0x97, 0x77, 0x7c, 0xfa, 0xa9, 0x09, 0xd0, 0xd7, + 0x26, 0x40, 0xb7, 0x4d, 0x80, 0x7e, 0x36, 0x01, 0xfa, 0xb8, 0x0a, 0xbc, 0xdb, 0x55, 0xe0, 0xfd, + 0x58, 0x05, 0xde, 0xeb, 0xc7, 0xa2, 0x34, 0x97, 0x8b, 0x8b, 0x38, 0x57, 0xb2, 0xbf, 0x80, 0xfe, + 0x73, 0x08, 0xc5, 0xdb, 0xe4, 0xca, 0x9d, 0x97, 0xb9, 0xae, 0x39, 0x5c, 0x0c, 0xbb, 0x1b, 0x78, + 0xfa, 0x27, 0x00, 0x00, 0xff, 0xff, 0xca, 0xdd, 0x50, 0x4d, 0x7c, 0x02, 0x00, 0x00, } func (this *MsgClaimResponse) Equal(that interface{}) bool { @@ -276,7 +278,7 @@ func (m *MsgClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { copy(dAtA[i:], m.AggSignature) i = encodeVarintTx(dAtA, i, uint64(len(m.AggSignature))) i-- - dAtA[i] = 0x3a + dAtA[i] = 0x42 } if len(m.VoteAddressSet) > 0 { for iNdEx := len(m.VoteAddressSet) - 1; iNdEx >= 0; iNdEx-- { @@ -285,27 +287,32 @@ func (m *MsgClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { } i = encodeVarintTx(dAtA, i, uint64(len(m.VoteAddressSet)*8)) i-- - dAtA[i] = 0x32 + dAtA[i] = 0x3a } if len(m.Payload) > 0 { i -= len(m.Payload) copy(dAtA[i:], m.Payload) i = encodeVarintTx(dAtA, i, uint64(len(m.Payload))) i-- - dAtA[i] = 0x2a + dAtA[i] = 0x32 } if m.Timestamp != 0 { i = encodeVarintTx(dAtA, i, uint64(m.Timestamp)) i-- - dAtA[i] = 0x20 + dAtA[i] = 0x28 } if m.Sequence != 0 { i = encodeVarintTx(dAtA, i, uint64(m.Sequence)) i-- + dAtA[i] = 0x20 + } + if m.DestChainId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.DestChainId)) + i-- dAtA[i] = 0x18 } - if m.ChainId != 0 { - i = encodeVarintTx(dAtA, i, uint64(m.ChainId)) + if m.SrcChainId != 0 { + i = encodeVarintTx(dAtA, i, uint64(m.SrcChainId)) i-- dAtA[i] = 0x10 } @@ -363,8 +370,11 @@ func (m *MsgClaim) Size() (n int) { if l > 0 { n += 1 + l + sovTx(uint64(l)) } - if m.ChainId != 0 { - n += 1 + sovTx(uint64(m.ChainId)) + if m.SrcChainId != 0 { + n += 1 + sovTx(uint64(m.SrcChainId)) + } + if m.DestChainId != 0 { + n += 1 + sovTx(uint64(m.DestChainId)) } if m.Sequence != 0 { n += 1 + sovTx(uint64(m.Sequence)) @@ -464,9 +474,9 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 2: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SrcChainId", wireType) } - m.ChainId = 0 + m.SrcChainId = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowTx @@ -476,12 +486,31 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ChainId |= uint32(b&0x7F) << shift + m.SrcChainId |= uint32(b&0x7F) << shift if b < 0x80 { break } } case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DestChainId", wireType) + } + m.DestChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DestChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) } @@ -500,7 +529,7 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { break } } - case 4: + case 5: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) } @@ -519,7 +548,7 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { break } } - case 5: + case 6: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field Payload", wireType) } @@ -553,7 +582,7 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { m.Payload = []byte{} } iNdEx = postIndex - case 6: + case 7: if wireType == 1 { var v uint64 if (iNdEx + 8) > l { @@ -605,7 +634,7 @@ func (m *MsgClaim) Unmarshal(dAtA []byte) error { } else { return fmt.Errorf("proto: wrong wireType = %d for field VoteAddressSet", wireType) } - case 7: + case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field AggSignature", wireType) } From 3f66a6ae739cb64d32e51842d62a72f910c33857 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 28 Dec 2022 20:24:34 +0800 Subject: [PATCH 22/50] add ut for bls sig --- go.mod | 3 +- go.sum | 1 + x/oracle/keeper/keeper.go | 17 ++-- x/oracle/keeper/keeper_test.go | 152 +++++++++++++++++++++++++++++---- x/oracle/testutil/bls.go | 110 ++++++++++++++++++++++++ 5 files changed, 257 insertions(+), 26 deletions(-) create mode 100644 x/oracle/testutil/bls.go diff --git a/go.mod b/go.mod index 2f624b9d28..d92fb93695 100644 --- a/go.mod +++ b/go.mod @@ -22,6 +22,7 @@ require ( github.com/cosmos/ledger-cosmos-go v0.11.1 github.com/ethereum/go-ethereum v1.10.19 github.com/evmos/ethermint v0.6.1-0.20220919141022-34226aa7b1fa + github.com/go-kit/kit v0.12.0 github.com/gogo/gateway v1.1.0 github.com/gogo/protobuf v1.3.3 github.com/golang/mock v1.6.0 @@ -58,6 +59,7 @@ require ( github.com/tendermint/tm-db v0.6.7 github.com/wealdtech/go-eth2-util v1.6.3 golang.org/x/crypto v0.1.0 + github.com/willf/bitset v1.1.3 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e golang.org/x/text v0.4.0 google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a @@ -94,7 +96,6 @@ require ( github.com/felixge/httpsnoop v1.0.1 // indirect github.com/ferranbt/fastssz v0.0.0-20210905181407-59cf6761a7d5 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect - github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect diff --git a/go.sum b/go.sum index 9c8d556bb1..83db7dcd24 100644 --- a/go.sum +++ b/go.sum @@ -1436,6 +1436,7 @@ github.com/whyrusleeping/go-logging v0.0.0-20170515211332-0457bb6b88fc/go.mod h1 github.com/whyrusleeping/mdns v0.0.0-20190826153040-b9b60ed33aa9/go.mod h1:j4l84WPFclQPj320J9gp0XwNKBb3U0zt5CBqjPp22G4= github.com/whyrusleeping/multiaddr-filter v0.0.0-20160516205228-e903e4adabd7/go.mod h1:X2c0RVCI1eSUFI8eLcY3c0423ykwiUdxLJtkDvruhjI= github.com/whyrusleeping/timecache v0.0.0-20160911033111-cfcb2f1abfee/go.mod h1:m2aV4LZI4Aez7dP5PMyVKEHhUyEJ/RjmPEDOpDvudHg= +github.com/willf/bitset v1.1.3 h1:ekJIKh6+YbUIVt9DfNbkR5d6aFcFTLDRyJNAACURBg8= github.com/willf/bitset v1.1.3/go.mod h1:RjeCKbqT1RxIR/KWY6phxZiaY1IyutSBfGjNPySAYV4= github.com/x-cray/logrus-prefixed-formatter v0.5.2/go.mod h1:2duySbKsL6M18s5GU7VPsoEPHyzalCE06qoARUCeBBE= github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 798449ee12..e68411a5b8 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -5,6 +5,7 @@ import ( sdkerrors "cosmossdk.io/errors" "github.com/prysmaticlabs/prysm/crypto/bls" + "github.com/tendermint/tendermint/libs/log" "github.com/willf/bitset" "github.com/cosmos/cosmos-sdk/codec" @@ -53,6 +54,11 @@ func NewKeeper( } } +// Logger inits the logger for cross chain module +func (k Keeper) Logger(ctx sdk.Context) log.Logger { + return ctx.Logger().With("module", "x/"+types.ModuleName) +} + // SetParams sets the params of oarcle module func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) @@ -70,11 +76,7 @@ func (k Keeper) GetRelayerParam(ctx sdk.Context) (uint64, uint64) { func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { var validatorIndex int64 = -1 for index, validator := range validators { - consAddr, err := validator.GetConsAddr() // TODO: update this - if err != nil { - return false, err - } - if consAddr.String() == claim.FromAddress { + if validator.RelayerAddress == claim.FromAddress { validatorIndex = int64(index) break } @@ -126,13 +128,12 @@ func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { continue } - // TODO: confirm the pub key - voteAddr, err := bls.PublicKeyFromBytes(val.ConsensusPubkey.Value) + votePubKey, err := bls.PublicKeyFromBytes(val.RelayerBlsKey) if err != nil { return sdkerrors.Wrapf(types.ErrBlsPubKey, fmt.Sprintf("BLS public key converts failed: %v", err)) } - votedPubKeys = append(votedPubKeys, voteAddr) + votedPubKeys = append(votedPubKeys, votePubKey) } // The valid voted validators should be no less than 2/3 validators. diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 7475f2002c..8f1cc16cad 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -1,20 +1,25 @@ package keeper_test import ( + "bytes" "testing" "time" - "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" - + "github.com/prysmaticlabs/prysm/crypto/bls" + "github.com/prysmaticlabs/prysm/crypto/bls/blst" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" tmtime "github.com/tendermint/tendermint/types/time" + "github.com/willf/bitset" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/testutil" "github.com/cosmos/cosmos-sdk/x/oracle/types" + "github.com/cosmos/cosmos-sdk/x/staking/teststaking" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -40,6 +45,83 @@ func TestTestSuite(t *testing.T) { suite.Run(t, new(TestSuite)) } +func (s *TestSuite) TestProcessClaim() { + s.app.OracleKeeper.SetParams(s.ctx, types.Params{ + RelayerTimeout: 5, + RelayerBackoffTime: 3, + }) + + _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) + + validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + validatorMap := make(map[string]int, 0) + for idx, validator := range validators { + validatorMap[validator.RelayerAddress] = idx + } + + msgClaim := types.MsgClaim{ + FromAddress: validators[0].RelayerAddress, + SrcChainId: 1, + DestChainId: 2, + Sequence: 1, + Timestamp: 1992, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + } + + blsSignBytes := msgClaim.GetBlsSignBytes() + + valBitSet := bitset.New(256) + for _, newValidator := range newValidators { + valBitSet.Set(uint(validatorMap[newValidator.RelayerAddress])) + } + + blsSig := testutil.GenerateBlsSig(blsKeys, blsSignBytes[:]) + msgClaim.VoteAddressSet = valBitSet.Bytes() + msgClaim.AggSignature = blsSig + + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + err := s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + s.Require().Nil(err, "error should be nil") + + // not in turn + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp)+6, 0)) + err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + s.Require().NotNil(err, "error should not be nil") + s.Require().Contains(err.Error(), "validator is not in turn") + + // wrong validator set + wrongValBitSet := bitset.New(256) + for i := 0; i < 10; i++ { + wrongValBitSet.Set(uint(i)) + } + msgClaim.VoteAddressSet = wrongValBitSet.Bytes() + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + s.Require().NotNil(err, "error should not be nil") + s.Require().Contains(err.Error(), "number of validator set is larger than validators") + + // wrong validator set + wrongValBitSet = bitset.New(256) + wrongValBitSet.Set(uint(validatorMap[newValidators[0].RelayerAddress])) + wrongValBitSet.Set(uint(validatorMap[newValidators[1].RelayerAddress])) + msgClaim.VoteAddressSet = wrongValBitSet.Bytes() + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + s.Require().NotNil(err, "error should not be nil") + s.Require().Contains(err.Error(), "not enough validators voted") + + // wrong sig + msgClaim.VoteAddressSet = valBitSet.Bytes() + msgClaim.AggSignature = bytes.Repeat([]byte{2}, 96) + + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + s.Require().NotNil(err, "error should not be nil") + s.Require().Contains(err.Error(), "BLS signature converts failed") +} + func (s *TestSuite) TestKeeper_IsValidatorInturn() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, @@ -49,13 +131,12 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { vals := make([]stakingtypes.Validator, 5) for i := range vals { pk := ed25519.GenPrivKey().PubKey() + vals[i] = newValidator(s.T(), sdk.ValAddress(pk.Address()), pk) } - val0Addr, err := vals[0].GetConsAddr() - s.Require().Nil(err) - val1Addr, err := vals[1].GetConsAddr() - s.Require().Nil(err) + val0Addr := vals[0].RelayerAddress + val1Addr := vals[1].RelayerAddress tests := []struct { claimMsg types.MsgClaim @@ -65,8 +146,9 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { }{ { types.MsgClaim{ - FromAddress: val0Addr.String(), - ChainId: 1, + FromAddress: val0Addr, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Timestamp: 1990, Payload: []byte("test payload"), @@ -80,8 +162,9 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { // wrong validator in timeout { types.MsgClaim{ - FromAddress: val1Addr.String(), - ChainId: 1, + FromAddress: val1Addr, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Timestamp: 1990, Payload: []byte("test payload"), @@ -95,8 +178,9 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { // right validator in backoff time { types.MsgClaim{ - FromAddress: val1Addr.String(), - ChainId: 1, + FromAddress: val1Addr, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Timestamp: 1985, Payload: []byte("test payload"), @@ -110,8 +194,9 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { // wrong validator in backoff time { types.MsgClaim{ - FromAddress: val0Addr.String(), - ChainId: 1, + FromAddress: val0Addr, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Timestamp: 1985, Payload: []byte("test payload"), @@ -125,8 +210,9 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { // right validator in backoff time { types.MsgClaim{ - FromAddress: val0Addr.String(), - ChainId: 1, + FromAddress: val0Addr, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Timestamp: 1970, Payload: []byte("test payload"), @@ -155,7 +241,39 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { // Creates a new validators and asserts the error check. func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) stakingtypes.Validator { - v, err := stakingtypes.NewValidator(operator, pubKey, stakingtypes.Description{}) + v, err := stakingtypes.NewSimpleValidator(operator, pubKey, stakingtypes.Description{}) require.NoError(t, err) return v } + +func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []stakingtypes.Validator, []bls.SecretKey) { + addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300)) + valAddrs := simapp.ConvertAddrsToValAddrs(addrs) + pks := simapp.CreateTestPubKeys(5) + + privKey1, _ := blst.RandKey() + privKey2, _ := blst.RandKey() + privKey3, _ := blst.RandKey() + + blsKeys := []bls.SecretKey{privKey1, privKey2, privKey3} + + val1 := teststaking.NewValidator(t, valAddrs[0], pks[0]) + val1.RelayerBlsKey = privKey1.PublicKey().Marshal() + + val2 := teststaking.NewValidator(t, valAddrs[1], pks[1]) + val2.RelayerBlsKey = privKey2.PublicKey().Marshal() + + val3 := teststaking.NewValidator(t, valAddrs[2], pks[2]) + val3.RelayerBlsKey = privKey3.PublicKey().Marshal() + + vals := []stakingtypes.Validator{val1, val2, val3} + + app.StakingKeeper.SetValidator(ctx, val1) + app.StakingKeeper.SetValidator(ctx, val2) + app.StakingKeeper.SetValidator(ctx, val3) + app.StakingKeeper.SetLastValidatorPower(ctx, val1.GetOperator(), 1) + app.StakingKeeper.SetLastValidatorPower(ctx, val2.GetOperator(), 2) + app.StakingKeeper.SetLastValidatorPower(ctx, val3.GetOperator(), 3) + + return addrs, valAddrs, vals, blsKeys +} diff --git a/x/oracle/testutil/bls.go b/x/oracle/testutil/bls.go new file mode 100644 index 0000000000..318813345a --- /dev/null +++ b/x/oracle/testutil/bls.go @@ -0,0 +1,110 @@ +package testutil + +import ( + "encoding/hex" + "fmt" + + "github.com/ethereum/go-ethereum/common" + "github.com/prysmaticlabs/prysm/crypto/bls" + "github.com/prysmaticlabs/prysm/crypto/bls/blst" + blscmn "github.com/prysmaticlabs/prysm/crypto/bls/common" +) + +type Vote struct { + PubKey [48]byte + Signature [96]byte +} + +func (vote *Vote) Verify(eventHash []byte) error { + blsPubKey, err := bls.PublicKeyFromBytes(vote.PubKey[:]) + + if err != nil { + return err + } + sig, err := bls.SignatureFromBytes(vote.Signature[:]) + + if err != nil { + return err + } + if !sig.Verify(blsPubKey, eventHash[:]) { + return fmt.Errorf("verify sig error") + } + return nil +} + +func AggregatedSignature(votes []*Vote) ([]byte, error) { + // Prepare aggregated vote signature + signatures := make([][]byte, 0, len(votes)) + for _, v := range votes { + signatures = append(signatures, v.Signature[:]) + } + sigs, err := bls.MultipleSignaturesFromBytes(signatures) + if err != nil { + return nil, err + } + return bls.AggregateSignatures(sigs).Marshal(), nil +} + +type VoteSigner struct { + privkey blscmn.SecretKey + pubKey blscmn.PublicKey +} + +func NewVoteSignerV2(privkey []byte) (*VoteSigner, error) { + privKey, err := blst.SecretKeyFromBytes(privkey) + if err != nil { + return nil, err + } + pubKey := privKey.PublicKey() + return &VoteSigner{ + privkey: privKey, + pubKey: pubKey, + }, nil +} + +// SignVote sign a vote, data is used to signed to generate the signature +func (signer *VoteSigner) SignVote(vote *Vote, data []byte) error { + signature := signer.privkey.Sign(data[:]) + copy(vote.PubKey[:], signer.pubKey.Marshal()[:]) + copy(vote.Signature[:], signature.Marshal()[:]) + return nil +} + +func GenerateBlsSig(privKeys []bls.SecretKey, data []byte) []byte { + privateKey1 := hex.EncodeToString(privKeys[0].Marshal()) + privateKey2 := hex.EncodeToString(privKeys[1].Marshal()) + privateKey3 := hex.EncodeToString(privKeys[2].Marshal()) + + validatorSigner1, _ := NewVoteSignerV2(common.Hex2Bytes(privateKey1)) + validatorSigner2, _ := NewVoteSignerV2(common.Hex2Bytes(privateKey2)) + validatorSigner3, _ := NewVoteSignerV2(common.Hex2Bytes(privateKey3)) + + var vote1 Vote + validatorSigner1.SignVote(&vote1, data) + err := vote1.Verify(data) + if err != nil { + panic("verify sig error") + } + + var vote2 Vote + validatorSigner2.SignVote(&vote2, data) + err = vote2.Verify(data) + if err != nil { + panic("verify sig error") + } + + var vote3 Vote + validatorSigner3.SignVote(&vote3, data) + err = vote2.Verify(data) + if err != nil { + panic("verify sig error") + } + + var votes []*Vote + votes = append(votes, &vote1) + votes = append(votes, &vote2) + votes = append(votes, &vote3) + + aggreatedSigature, _ := AggregatedSignature(votes) + return aggreatedSigature +} From ddd5ec654ff5e6bed83ee8af4804f898eb11d7df Mon Sep 17 00:00:00 2001 From: yutianwu Date: Thu, 29 Dec 2022 16:00:50 +0800 Subject: [PATCH 23/50] fix some issue and add msg server tests --- proto/cosmos/oracle/v1/event.proto | 2 +- simapp/app.go | 1 + types/cross_chain.go | 6 +- x/crosschain/testutil/mockapp.go | 6 +- x/oracle/keeper/keeper_test.go | 17 ++++ x/oracle/keeper/msg_server.go | 25 +++-- x/oracle/keeper/msg_server_test.go | 147 +++++++++++++++++++++++++++++ x/oracle/types/event.pb.go | 86 ++++++++++------- x/oracle/types/expected_keepers.go | 1 + x/oracle/types/msgs_test.go | 74 ++++++++++----- 10 files changed, 285 insertions(+), 80 deletions(-) create mode 100644 x/oracle/keeper/msg_server_test.go diff --git a/proto/cosmos/oracle/v1/event.proto b/proto/cosmos/oracle/v1/event.proto index 080a17ba5c..ce40f03749 100644 --- a/proto/cosmos/oracle/v1/event.proto +++ b/proto/cosmos/oracle/v1/event.proto @@ -14,5 +14,5 @@ message EventPackageClaim { int64 send_sequence = 5; bool crash = 6; string error_msg = 7; - int64 fee = 8; + string relay_fee = 8; } \ No newline at end of file diff --git a/simapp/app.go b/simapp/app.go index 661dcfe03e..823aa48b4b 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -146,6 +146,7 @@ var ( stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, nft.ModuleName: nil, + crosschaintypes.ModuleName: nil, } ) diff --git a/types/cross_chain.go b/types/cross_chain.go index 2cab476073..28a6312207 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -53,7 +53,7 @@ func ParseChainID(input string) (ChainID, error) { } type CrossChainApplication interface { - ExecuteSynPackage(ctx Context, payload []byte, relayerFee int64) ExecuteResult + ExecuteSynPackage(ctx Context, payload []byte, relayerFee *big.Int) ExecuteResult ExecuteAckPackage(ctx Context, payload []byte) ExecuteResult // When the ack application crash, payload is the payload of the origin package. ExecuteFailAckPackage(ctx Context, payload []byte) ExecuteResult @@ -89,7 +89,7 @@ func EncodePackageHeader(packageType CrossChainPackageType, timestamp uint64, re timestampBytes := make([]byte, TimestampLength) binary.BigEndian.PutUint64(timestampBytes, timestamp) - copy(packageHeader[CrossChainFeeLength:CrossChainFeeLength+TimestampLength], timestampBytes) + copy(packageHeader[PackageTypeLength:PackageTypeLength+TimestampLength], timestampBytes) length := len(relayerFee.Bytes()) copy(packageHeader[PackageHeaderLength-length:PackageHeaderLength], relayerFee.Bytes()) @@ -103,7 +103,7 @@ func DecodePackageHeader(packageHeader []byte) (packageType CrossChainPackageTyp } packageType = CrossChainPackageType(packageHeader[0]) - timestamp = binary.BigEndian.Uint64(packageHeader[PackageTypeLength : CrossChainFeeLength+TimestampLength]) + timestamp = binary.BigEndian.Uint64(packageHeader[PackageTypeLength : PackageTypeLength+TimestampLength]) relayFee.SetBytes(packageHeader[PackageTypeLength+TimestampLength : PackageHeaderLength]) return diff --git a/x/crosschain/testutil/mockapp.go b/x/crosschain/testutil/mockapp.go index 8ed4f3f396..0b09dc9adb 100644 --- a/x/crosschain/testutil/mockapp.go +++ b/x/crosschain/testutil/mockapp.go @@ -3,10 +3,12 @@ package testutil import ( + "math/big" reflect "reflect" - types "github.com/cosmos/cosmos-sdk/types" gomock "github.com/golang/mock/gomock" + + types "github.com/cosmos/cosmos-sdk/types" ) // MockCrossChainApplication is a mock of CrossChainApplication interface @@ -33,7 +35,7 @@ func (m *MockCrossChainApplication) EXPECT() *MockCrossChainApplicationMockRecor } // ExecuteSynPackage mocks base method -func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, payload []byte, relayerFee int64) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, payload []byte, relayerFee *big.Int) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteSynPackage", ctx, payload, relayerFee) ret0, _ := ret[0].(types.ExecuteResult) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 8f1cc16cad..4a4816283b 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -13,6 +13,11 @@ import ( tmtime "github.com/tendermint/tendermint/types/time" "github.com/willf/bitset" + crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" + + "github.com/cosmos/cosmos-sdk/x/oracle/keeper" + "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/simapp" @@ -28,6 +33,8 @@ type TestSuite struct { app *simapp.SimApp ctx sdk.Context + + msgServer types.MsgServer } func (s *TestSuite) SetupTest() { @@ -39,6 +46,16 @@ func (s *TestSuite) SetupTest() { s.app = app s.ctx = ctx + + s.app.CrossChainKeeper.SetSrcChainID(sdk.ChainID(1)) + + coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100000))) + err := s.app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins) + s.NoError(err) + err = app.BankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, crosschaintypes.ModuleName, coins) + s.NoError(err) + + s.msgServer = keeper.NewMsgServerImpl(s.app.OracleKeeper) } func TestTestSuite(t *testing.T) { diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 0d0d520ac6..ee72097a3c 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -4,6 +4,7 @@ import ( "context" "encoding/hex" "fmt" + "math/big" "runtime/debug" sdkerrors "cosmossdk.io/errors" @@ -31,6 +32,8 @@ var _ types.MsgServer = msgServer{} func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.MsgClaimResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) + logger := k.oracleKeeper.Logger(ctx) + // check dest chain id if sdk.ChainID(req.DestChainId) != k.oracleKeeper.CrossChainKeeper.GetSrcChainID() { return nil, sdkerrors.Wrapf(types.ErrInvalidDestChainId, fmt.Sprintf("dest chain id(%d) should be %d", req.SrcChainId, k.oracleKeeper.CrossChainKeeper.GetSrcChainID())) @@ -57,10 +60,10 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) if err != nil { // only do log, but let reset package get chance to execute. - ctx.Logger().With("module", "oracle").Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) + logger.Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) return nil, err } - ctx.Logger().With("module", "oracle").Info(fmt.Sprintf("process package success, channel=%d, sequence=%d", pack.ChannelId, pack.Sequence)) + logger.Info(fmt.Sprintf("process package success, channel=%d, sequence=%d", pack.ChannelId, pack.Sequence)) events = append(events, event) @@ -74,7 +77,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg } func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*types.EventPackageClaim, error) { - logger := ctx.Logger().With("module", "x/oracle") + logger := oracleKeeper.Logger(ctx) crossChainApp := oracleKeeper.CrossChainKeeper.GetCrossChainApp(pack.ChannelId) if crossChainApp == nil { @@ -92,26 +95,22 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch } if timestamp != req.Timestamp { - return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp is not the same in payload header") + return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, timestamp) } if !sdk.IsValidCrossChainPackageType(packageType) { return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageType)) } - feeAmount := relayFee.Int64() - if feeAmount < 0 { - return nil, sdkerrors.Wrapf(types.ErrFeeOverflow, fmt.Sprintf("fee(%s) is overflow", relayFee.String())) - } - - fee := sdk.Coins{sdk.Coin{Denom: sdk.NativeTokenSymbol, Amount: sdk.NewInt(feeAmount)}} + bondDenom := oracleKeeper.StakingKeeper.BondDenom(ctx) + fee := sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(&relayFee)}} err = oracleKeeper.SendCoinsToFeeCollector(ctx, fee) if err != nil { return nil, err } cacheCtx, write := ctx.CacheContext() - crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageType, feeAmount) + crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageType, &relayFee) if result.IsOk() { write() } else { @@ -156,7 +155,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch PackageType: uint32(packageType), ReceiveSequence: pack.Sequence, SendSequence: sendSequence, - Fee: feeAmount, + RelayFee: relayFee.String(), Crash: crash, ErrorMsg: result.ErrMsg(), } @@ -164,7 +163,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch return claimEvent, nil } -func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, packageType sdk.CrossChainPackageType, relayerFee int64) (crash bool, result sdk.ExecuteResult) { +func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, packageType sdk.CrossChainPackageType, relayerFee *big.Int) (crash bool, result sdk.ExecuteResult) { defer func() { if r := recover(); r != nil { log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack())) diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go new file mode 100644 index 0000000000..e0fdddad0f --- /dev/null +++ b/x/oracle/keeper/msg_server_test.go @@ -0,0 +1,147 @@ +package keeper_test + +import ( + "math/big" + "time" + + "github.com/willf/bitset" + + "github.com/cosmos/cosmos-sdk/bsc/rlp" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/testutil" + "github.com/cosmos/cosmos-sdk/x/oracle/types" +) + +type DummyCrossChainApp struct { +} + +func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, payload []byte, relayerFee *big.Int) sdk.ExecuteResult { + return sdk.ExecuteResult{} +} + +func (ta *DummyCrossChainApp) ExecuteAckPackage(ctx sdk.Context, payload []byte) sdk.ExecuteResult { + return sdk.ExecuteResult{} +} + +func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, payload []byte) sdk.ExecuteResult { + return sdk.ExecuteResult{} +} + +func (s *TestSuite) TestClaim() { + s.app.CrossChainKeeper.RegisterChannel("test", sdk.ChannelID(1), &DummyCrossChainApp{}) + + s.app.OracleKeeper.SetParams(s.ctx, types.Params{ + RelayerTimeout: 5, + RelayerBackoffTime: 3, + }) + + _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) + + validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + validatorMap := make(map[string]int, 0) + for idx, validator := range validators { + validatorMap[validator.RelayerAddress] = idx + } + + payloadHeader := sdk.EncodePackageHeader(sdk.SynCrossChainPackageType, 1992, *big.NewInt(1)) + + testPackage := types.Package{ + ChannelId: 1, + Sequence: 0, + Payload: append(payloadHeader, []byte("test payload")...), + } + + packageBytes, err := rlp.EncodeToBytes([]types.Package{testPackage}) + s.Require().Nil(err, "encode package error") + + msgClaim := types.MsgClaim{ + FromAddress: validators[0].RelayerAddress, + SrcChainId: 56, + DestChainId: 1, + Sequence: 0, + Timestamp: 1992, + Payload: packageBytes, + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + } + + blsSignBytes := msgClaim.GetBlsSignBytes() + + valBitSet := bitset.New(256) + for _, newValidator := range newValidators { + valBitSet.Set(uint(validatorMap[newValidator.RelayerAddress])) + } + + blsSig := testutil.GenerateBlsSig(blsKeys, blsSignBytes[:]) + msgClaim.VoteAddressSet = valBitSet.Bytes() + msgClaim.AggSignature = blsSig + + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + _, err = s.msgServer.Claim(s.ctx, &msgClaim) + s.Require().Nil(err, "process claim msg error") +} + +func (s *TestSuite) TestInvalidClaim() { + s.app.CrossChainKeeper.RegisterChannel("test", sdk.ChannelID(1), &DummyCrossChainApp{}) + + s.app.OracleKeeper.SetParams(s.ctx, types.Params{ + RelayerTimeout: 5, + RelayerBackoffTime: 3, + }) + + _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) + + validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + validatorMap := make(map[string]int, 0) + for idx, validator := range validators { + validatorMap[validator.RelayerAddress] = idx + } + + msgClaim := types.MsgClaim{ + FromAddress: validators[0].RelayerAddress, + SrcChainId: 56, + DestChainId: 1, + Sequence: 0, + Timestamp: 1992, + Payload: []byte("invalid payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + } + + blsSignBytes := msgClaim.GetBlsSignBytes() + + valBitSet := bitset.New(256) + for _, newValidator := range newValidators { + valBitSet.Set(uint(validatorMap[newValidator.RelayerAddress])) + } + + blsSig := testutil.GenerateBlsSig(blsKeys, blsSignBytes[:]) + msgClaim.VoteAddressSet = valBitSet.Bytes() + msgClaim.AggSignature = blsSig + + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + _, err := s.msgServer.Claim(s.ctx, &msgClaim) + s.Require().NotNil(err, "process claim should return error") + s.Require().Contains(err.Error(), "decode payload error") + + // invalid timestamp + payloadHeader := sdk.EncodePackageHeader(sdk.SynCrossChainPackageType, 1993, *big.NewInt(1)) + testPackage := types.Package{ + ChannelId: 1, + Sequence: 0, + Payload: append(payloadHeader, []byte("test payload")...), + } + + packageBytes, err := rlp.EncodeToBytes([]types.Package{testPackage}) + s.Require().Nil(err, "encode package error") + + msgClaim.Payload = packageBytes + blsSignBytes = msgClaim.GetBlsSignBytes() + blsSig = testutil.GenerateBlsSig(blsKeys, blsSignBytes[:]) + msgClaim.AggSignature = blsSig + + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + _, err = s.msgServer.Claim(s.ctx, &msgClaim) + s.Require().NotNil(err, "process claim should return error") + s.Require().Contains(err.Error(), "is not the same in payload header") +} diff --git a/x/oracle/types/event.pb.go b/x/oracle/types/event.pb.go index 0efefc03d6..c296cee58c 100644 --- a/x/oracle/types/event.pb.go +++ b/x/oracle/types/event.pb.go @@ -31,7 +31,7 @@ type EventPackageClaim struct { SendSequence int64 `protobuf:"varint,5,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` Crash bool `protobuf:"varint,6,opt,name=crash,proto3" json:"crash,omitempty"` ErrorMsg string `protobuf:"bytes,7,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` - Fee int64 `protobuf:"varint,8,opt,name=fee,proto3" json:"fee,omitempty"` + RelayFee string `protobuf:"bytes,8,opt,name=relay_fee,json=relayFee,proto3" json:"relay_fee,omitempty"` } func (m *EventPackageClaim) Reset() { *m = EventPackageClaim{} } @@ -116,11 +116,11 @@ func (m *EventPackageClaim) GetErrorMsg() string { return "" } -func (m *EventPackageClaim) GetFee() int64 { +func (m *EventPackageClaim) GetRelayFee() string { if m != nil { - return m.Fee + return m.RelayFee } - return 0 + return "" } func init() { @@ -130,28 +130,28 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/event.proto", fileDescriptor_3e254cedc4112fb0) } var fileDescriptor_3e254cedc4112fb0 = []byte{ - // 321 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xbb, 0x4e, 0xc3, 0x30, - 0x14, 0x86, 0xeb, 0x5e, 0x53, 0xd3, 0x8a, 0x62, 0x31, 0xa4, 0x5c, 0xa2, 0x00, 0x4b, 0x10, 0x22, - 0x51, 0xc5, 0x1b, 0x80, 0x3a, 0x74, 0x40, 0x42, 0x81, 0x89, 0x25, 0x72, 0x9d, 0x43, 0x12, 0xb5, - 0x89, 0x83, 0x9d, 0x46, 0xf4, 0x01, 0xd8, 0x79, 0x2c, 0xc6, 0x8e, 0x8c, 0xa8, 0x7d, 0x11, 0x14, - 0xc7, 0xc0, 0x94, 0xfc, 0xdf, 0xf7, 0xfb, 0x48, 0x3e, 0xc6, 0x27, 0x8c, 0xcb, 0x94, 0x4b, 0x8f, - 0x0b, 0xca, 0x96, 0xe0, 0x95, 0x13, 0x0f, 0x4a, 0xc8, 0x0a, 0x37, 0x17, 0xbc, 0xe0, 0x64, 0x54, - 0x5b, 0xb7, 0xb6, 0x6e, 0x39, 0x39, 0x1a, 0xd7, 0x24, 0x50, 0xde, 0xd3, 0x5a, 0x85, 0xf3, 0xf7, - 0x26, 0x3e, 0x98, 0x56, 0x87, 0x1f, 0x28, 0x5b, 0xd0, 0x08, 0xee, 0x96, 0x34, 0x49, 0xc9, 0x18, - 0x1b, 0x2c, 0xa6, 0x49, 0x16, 0x24, 0xa1, 0x89, 0x6c, 0xe4, 0x0c, 0xfd, 0x9e, 0xca, 0xb3, 0x90, - 0x9c, 0x62, 0xcc, 0x62, 0x9a, 0x65, 0xb0, 0xac, 0x64, 0x53, 0xc9, 0xbe, 0x26, 0xb3, 0x90, 0x9c, - 0xe1, 0x41, 0x5e, 0x4f, 0x0a, 0x8a, 0x75, 0x0e, 0x66, 0x4b, 0x15, 0xf6, 0x34, 0x7b, 0x5a, 0xe7, - 0x40, 0x2e, 0xf1, 0x48, 0x00, 0x83, 0xa4, 0x84, 0x40, 0xc2, 0xeb, 0x0a, 0x32, 0x06, 0x66, 0xdb, - 0x46, 0x4e, 0xdb, 0xdf, 0xd7, 0xfc, 0x51, 0x63, 0x72, 0x81, 0x87, 0x12, 0xb2, 0xf0, 0xbf, 0xd7, - 0xb1, 0x91, 0xd3, 0xf2, 0x07, 0x15, 0xfc, 0x2b, 0x1d, 0xe2, 0x0e, 0x13, 0x54, 0xc6, 0x66, 0xd7, - 0x46, 0x8e, 0xe1, 0xd7, 0x81, 0x1c, 0xe3, 0x3e, 0x08, 0xc1, 0x45, 0x90, 0xca, 0xc8, 0xec, 0xd9, - 0xc8, 0xe9, 0xfb, 0x86, 0x02, 0xf7, 0x32, 0x22, 0x23, 0xdc, 0x7a, 0x01, 0x30, 0x0d, 0x35, 0xad, - 0xfa, 0xbd, 0x9d, 0x7e, 0x6e, 0x2d, 0xb4, 0xd9, 0x5a, 0xe8, 0x7b, 0x6b, 0xa1, 0x8f, 0x9d, 0xd5, - 0xd8, 0xec, 0xac, 0xc6, 0xd7, 0xce, 0x6a, 0x3c, 0x5f, 0x45, 0x49, 0x11, 0xaf, 0xe6, 0x2e, 0xe3, - 0xa9, 0x5e, 0x9d, 0xfe, 0x5c, 0xcb, 0x70, 0xe1, 0xbd, 0xfd, 0x3e, 0x42, 0x75, 0x5b, 0x39, 0xef, - 0xaa, 0xad, 0xde, 0xfc, 0x04, 0x00, 0x00, 0xff, 0xff, 0x51, 0xea, 0x27, 0x3a, 0xa2, 0x01, 0x00, - 0x00, + // 326 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xcd, 0x4e, 0xe3, 0x30, + 0x14, 0x85, 0xeb, 0xfe, 0xa6, 0x9e, 0x56, 0xd3, 0xb1, 0x66, 0x91, 0xce, 0x40, 0x14, 0x60, 0x13, + 0x84, 0x48, 0x54, 0xf1, 0x06, 0xa0, 0x22, 0x75, 0x81, 0x84, 0x02, 0x2b, 0x36, 0x91, 0xeb, 0x5c, + 0x92, 0xa8, 0x49, 0x1c, 0xec, 0x34, 0xa2, 0x6f, 0xd1, 0xc7, 0x62, 0xd9, 0x25, 0x4b, 0xd4, 0xbe, + 0x08, 0x8a, 0x63, 0x60, 0x65, 0x9d, 0xef, 0x3b, 0xb6, 0xe4, 0x7b, 0xf1, 0x11, 0xe3, 0x32, 0xe3, + 0xd2, 0xe3, 0x82, 0xb2, 0x14, 0xbc, 0x6a, 0xe6, 0x41, 0x05, 0x79, 0xe9, 0x16, 0x82, 0x97, 0x9c, + 0x4c, 0x1a, 0xeb, 0x36, 0xd6, 0xad, 0x66, 0xff, 0xa6, 0x0d, 0x09, 0x94, 0xf7, 0xb4, 0x56, 0xe1, + 0x74, 0xdb, 0xc6, 0x7f, 0xe6, 0xf5, 0xe5, 0x7b, 0xca, 0x56, 0x34, 0x82, 0x9b, 0x94, 0x26, 0x19, + 0x99, 0x62, 0x83, 0xc5, 0x34, 0xc9, 0x83, 0x24, 0x34, 0x91, 0x8d, 0x9c, 0xb1, 0x3f, 0x50, 0x79, + 0x11, 0x92, 0x63, 0x8c, 0x59, 0x4c, 0xf3, 0x1c, 0xd2, 0x5a, 0xb6, 0x95, 0x1c, 0x6a, 0xb2, 0x08, + 0xc9, 0x09, 0x1e, 0x15, 0xcd, 0x4b, 0x41, 0xb9, 0x29, 0xc0, 0xec, 0xa8, 0xc2, 0x2f, 0xcd, 0x1e, + 0x37, 0x05, 0x90, 0x73, 0x3c, 0x11, 0xc0, 0x20, 0xa9, 0x20, 0x90, 0xf0, 0xb2, 0x86, 0x9c, 0x81, + 0xd9, 0xb5, 0x91, 0xd3, 0xf5, 0x7f, 0x6b, 0xfe, 0xa0, 0x31, 0x39, 0xc3, 0x63, 0x09, 0x79, 0xf8, + 0xd3, 0xeb, 0xd9, 0xc8, 0xe9, 0xf8, 0xa3, 0x1a, 0x7e, 0x97, 0xfe, 0xe2, 0x1e, 0x13, 0x54, 0xc6, + 0x66, 0xdf, 0x46, 0x8e, 0xe1, 0x37, 0x81, 0xfc, 0xc7, 0x43, 0x10, 0x82, 0x8b, 0x20, 0x93, 0x91, + 0x39, 0xb0, 0x91, 0x33, 0xf4, 0x0d, 0x05, 0xee, 0x64, 0x54, 0x4b, 0x01, 0x29, 0xdd, 0x04, 0xcf, + 0x00, 0xa6, 0xd1, 0x48, 0x05, 0x6e, 0x01, 0xae, 0xe7, 0x6f, 0x7b, 0x0b, 0xed, 0xf6, 0x16, 0xfa, + 0xd8, 0x5b, 0x68, 0x7b, 0xb0, 0x5a, 0xbb, 0x83, 0xd5, 0x7a, 0x3f, 0x58, 0xad, 0xa7, 0x8b, 0x28, + 0x29, 0xe3, 0xf5, 0xd2, 0x65, 0x3c, 0xd3, 0x53, 0xd4, 0xc7, 0xa5, 0x0c, 0x57, 0xde, 0xeb, 0xd7, + 0x3e, 0xea, 0x8f, 0xcb, 0x65, 0x5f, 0x0d, 0xf8, 0xea, 0x33, 0x00, 0x00, 0xff, 0xff, 0xb7, 0xa8, + 0xb1, 0xcb, 0xad, 0x01, 0x00, 0x00, } func (m *EventPackageClaim) Marshal() (dAtA []byte, err error) { @@ -174,10 +174,12 @@ func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if m.Fee != 0 { - i = encodeVarintEvent(dAtA, i, uint64(m.Fee)) + if len(m.RelayFee) > 0 { + i -= len(m.RelayFee) + copy(dAtA[i:], m.RelayFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.RelayFee))) i-- - dAtA[i] = 0x40 + dAtA[i] = 0x42 } if len(m.ErrorMsg) > 0 { i -= len(m.ErrorMsg) @@ -263,8 +265,9 @@ func (m *EventPackageClaim) Size() (n int) { if l > 0 { n += 1 + l + sovEvent(uint64(l)) } - if m.Fee != 0 { - n += 1 + sovEvent(uint64(m.Fee)) + l = len(m.RelayFee) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) } return n } @@ -452,10 +455,10 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { m.ErrorMsg = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 8: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Fee", wireType) + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayFee", wireType) } - m.Fee = 0 + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowEvent @@ -465,11 +468,24 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.Fee |= int64(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthEvent + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RelayFee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipEvent(dAtA[iNdEx:]) diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 883bf0933d..a048efa221 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -7,6 +7,7 @@ import ( type StakingKeeper interface { GetLastValidators(ctx sdk.Context) (validators []types.Validator) + BondDenom(ctx sdk.Context) (res string) } type CrossChainKeeper interface { diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index 1c1dcfd691..608bad92b6 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -1,4 +1,4 @@ -package types +package types_test import ( "bytes" @@ -13,19 +13,21 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/hd" "github.com/cosmos/cosmos-sdk/simapp" "github.com/cosmos/cosmos-sdk/testutil" + "github.com/cosmos/cosmos-sdk/x/oracle/types" ) func TestBlsClaim(t *testing.T) { - claim := &BlsClaim{ - ChainId: 1, - Sequence: 1, - Timestamp: 1000, - Payload: []byte("test payload"), + claim := &types.BlsClaim{ + SrcChainId: 1, + DestChainId: 2, + Sequence: 1, + Timestamp: 1000, + Payload: []byte("test payload"), } signBytes := claim.GetSignBytes() - require.Equal(t, "954d4fe4c768c275f14ef32929ab83e182a4de3c0aef38964efdf0bc8f76eaff", + require.Equal(t, "0a0b49ef40324d4c511d7a81e1edeeccaa10b768e55cece473b5cd99137f05f6", hex.EncodeToString(signBytes[:])) } @@ -35,14 +37,15 @@ func TestValidateBasic(t *testing.T) { require.NoError(t, err) tests := []struct { - claimMsg MsgClaim + claimMsg types.MsgClaim expectedPass bool errorMsg string }{ { - MsgClaim{ + types.MsgClaim{ FromAddress: "random string", - ChainId: 1, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1}, @@ -52,9 +55,10 @@ func TestValidateBasic(t *testing.T) { "invalid from address", }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: math.MaxUint16 + 1, + SrcChainId: math.MaxUint16 + 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1}, @@ -64,9 +68,23 @@ func TestValidateBasic(t *testing.T) { "chain id should not be larger than", }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: 100, + SrcChainId: 1, + DestChainId: math.MaxUint16 + 1, + Sequence: 1, + Payload: []byte("test payload"), + VoteAddressSet: []uint64{0, 1}, + AggSignature: []byte("test sig"), + }, + false, + "chain id should not be larger than", + }, + { + types.MsgClaim{ + FromAddress: addr.String(), + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte{}, VoteAddressSet: []uint64{0, 1}, @@ -76,49 +94,53 @@ func TestValidateBasic(t *testing.T) { "payload should not be empty", }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: 100, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1}, AggSignature: []byte("test sig"), }, false, - fmt.Sprintf("length of vote addresse set should be %d", ValidatorBitSetLength), + fmt.Sprintf("length of vote addresse set should be %d", types.ValidatorBitSetLength), }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: 100, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1, 2, 3}, AggSignature: []byte("test sig"), }, false, - fmt.Sprintf("length of signature should be %d", BLSSignatureLength), + fmt.Sprintf("length of signature should be %d", types.BLSSignatureLength), }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: 100, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1, 2, 3}, - AggSignature: bytes.Repeat([]byte{0}, BLSSignatureLength), + AggSignature: bytes.Repeat([]byte{0}, types.BLSSignatureLength), }, false, "timestamp should not be 0", }, { - MsgClaim{ + types.MsgClaim{ FromAddress: addr.String(), - ChainId: 100, + SrcChainId: 1, + DestChainId: 2, Sequence: 1, Payload: []byte("test payload"), VoteAddressSet: []uint64{0, 1, 2, 3}, - AggSignature: bytes.Repeat([]byte{0}, BLSSignatureLength), + AggSignature: bytes.Repeat([]byte{0}, types.BLSSignatureLength), Timestamp: uint64(time.Now().Unix()), }, true, From 2a0803b5b3b05f2cd21161e1e5e6b76164c1d701 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Thu, 29 Dec 2022 19:59:24 +0800 Subject: [PATCH 24/50] update tests --- x/crosschain/keeper/keeper.go | 12 +++++++++++- x/oracle/keeper/keeper.go | 6 +++++- x/oracle/keeper/keeper_test.go | 6 ++++++ x/oracle/keeper/msg_server.go | 7 ++++++- x/oracle/keeper/msg_server_test.go | 23 +++++++++++++++++++++++ x/oracle/types/errors.go | 2 +- x/oracle/types/expected_keepers.go | 2 ++ 7 files changed, 54 insertions(+), 4 deletions(-) diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index abf9e84c38..8dd0ccdcb0 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -131,7 +131,7 @@ func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChai return nil } -// RegisterDestChain registers a chain with name +// RegisterDestChain registers a dest chain func (k Keeper) RegisterDestChain(chainID sdk.ChainID) error { for _, chain := range k.cfg.destChains { if chainID == chain { @@ -143,6 +143,16 @@ func (k Keeper) RegisterDestChain(chainID sdk.ChainID) error { return nil } +// IsDestChainSupported returns the support status of a dest chain +func (k Keeper) IsDestChainSupported(chainID sdk.ChainID) bool { + for _, chain := range k.cfg.destChains { + if chainID == chain { + return true + } + } + return false +} + // SetChannelSendPermission sets the channel send permission func (k Keeper) SetChannelSendPermission(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, permission sdk.ChannelPermission) { kvStore := ctx.KVStore(k.storeKey) diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index e68411a5b8..051ec7c189 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -107,7 +107,11 @@ func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Val // ProcessClaim checks the bls signature func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { - validators := k.StakingKeeper.GetLastValidators(ctx) + historicalInfo, ok := k.StakingKeeper.GetHistoricalInfo(ctx, ctx.BlockHeight()) + if !ok { + return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("get historical validators failed")) + } + validators := historicalInfo.Valset inturn, err := k.IsValidatorInturn(ctx, validators, claim) if err != nil { diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 4a4816283b..c54ad6fc54 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -71,6 +71,12 @@ func (s *TestSuite) TestProcessClaim() { _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + + s.app.StakingKeeper.SetHistoricalInfo(s.ctx, s.ctx.BlockHeight(), &stakingtypes.HistoricalInfo{ + Header: s.ctx.BlockHeader(), + Valset: validators, + }) + validatorMap := make(map[string]int, 0) for idx, validator := range validators { validatorMap[validator.RelayerAddress] = idx diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index ee72097a3c..c05292ec1e 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -36,7 +36,12 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg // check dest chain id if sdk.ChainID(req.DestChainId) != k.oracleKeeper.CrossChainKeeper.GetSrcChainID() { - return nil, sdkerrors.Wrapf(types.ErrInvalidDestChainId, fmt.Sprintf("dest chain id(%d) should be %d", req.SrcChainId, k.oracleKeeper.CrossChainKeeper.GetSrcChainID())) + return nil, sdkerrors.Wrapf(types.ErrInvalidDestChainId, fmt.Sprintf("dest chain id(%d) should be %d", req.DestChainId, k.oracleKeeper.CrossChainKeeper.GetSrcChainID())) + } + + // check src chain id + if !k.oracleKeeper.CrossChainKeeper.IsDestChainSupported(sdk.ChainID(req.SrcChainId)) { + return nil, sdkerrors.Wrapf(types.ErrInvalidSrcChainId, fmt.Sprintf("src chain id(%d) is not supported", req.SrcChainId)) } sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), types.RelayPackagesChannelId) diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index e0fdddad0f..10a41f6060 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -10,6 +10,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/oracle/testutil" "github.com/cosmos/cosmos-sdk/x/oracle/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) type DummyCrossChainApp struct { @@ -29,6 +30,7 @@ func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, payload []b func (s *TestSuite) TestClaim() { s.app.CrossChainKeeper.RegisterChannel("test", sdk.ChannelID(1), &DummyCrossChainApp{}) + s.app.CrossChainKeeper.RegisterDestChain(sdk.ChainID(56)) s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, @@ -38,6 +40,12 @@ func (s *TestSuite) TestClaim() { _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + + s.app.StakingKeeper.SetHistoricalInfo(s.ctx, s.ctx.BlockHeight(), &stakingtypes.HistoricalInfo{ + Header: s.ctx.BlockHeader(), + Valset: validators, + }) + validatorMap := make(map[string]int, 0) for idx, validator := range validators { validatorMap[validator.RelayerAddress] = idx @@ -92,6 +100,12 @@ func (s *TestSuite) TestInvalidClaim() { _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) validators := s.app.StakingKeeper.GetLastValidators(s.ctx) + + s.app.StakingKeeper.SetHistoricalInfo(s.ctx, s.ctx.BlockHeight(), &stakingtypes.HistoricalInfo{ + Header: s.ctx.BlockHeader(), + Valset: validators, + }) + validatorMap := make(map[string]int, 0) for idx, validator := range validators { validatorMap[validator.RelayerAddress] = idx @@ -119,9 +133,18 @@ func (s *TestSuite) TestInvalidClaim() { msgClaim.VoteAddressSet = valBitSet.Bytes() msgClaim.AggSignature = blsSig + // invalid src chain id s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) _, err := s.msgServer.Claim(s.ctx, &msgClaim) s.Require().NotNil(err, "process claim should return error") + s.Require().Contains(err.Error(), "src chain id is invalid") + + s.app.CrossChainKeeper.RegisterDestChain(sdk.ChainID(56)) + + // invalid payload + s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) + _, err = s.msgServer.Claim(s.ctx, &msgClaim) + s.Require().NotNil(err, "process claim should return error") s.Require().Contains(err.Error(), "decode payload error") // invalid timestamp diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index bd2005a431..71aa61c235 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -7,7 +7,6 @@ var ( ErrInvalidReceiveSequence = sdkerrors.Register(ModuleName, 2, "receive sequence is invalid") ErrInvalidPayloadHeader = sdkerrors.Register(ModuleName, 3, "payload header is invalid") ErrInvalidPackageType = sdkerrors.Register(ModuleName, 4, "package type is invalid") - ErrFeeOverflow = sdkerrors.Register(ModuleName, 5, "fee is overflow") ErrInvalidPackage = sdkerrors.Register(ModuleName, 6, "package is invalid") ErrInvalidPayload = sdkerrors.Register(ModuleName, 7, "payload is invalid") ErrValidatorSet = sdkerrors.Register(ModuleName, 8, "validator set is invalid") @@ -17,4 +16,5 @@ var ( ErrNotValidator = sdkerrors.Register(ModuleName, 12, "sender is not validator") ErrValidatorNotInTurn = sdkerrors.Register(ModuleName, 13, "validator is not in turn") ErrInvalidDestChainId = sdkerrors.Register(ModuleName, 14, "dest chain id is invalid") + ErrInvalidSrcChainId = sdkerrors.Register(ModuleName, 15, "src chain id is invalid") ) diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index a048efa221..927060786f 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -7,6 +7,7 @@ import ( type StakingKeeper interface { GetLastValidators(ctx sdk.Context) (validators []types.Validator) + GetHistoricalInfo(ctx sdk.Context, height int64) (types.HistoricalInfo, bool) BondDenom(ctx sdk.Context) (res string) } @@ -15,6 +16,7 @@ type CrossChainKeeper interface { packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication GetSrcChainID() sdk.ChainID + IsDestChainSupported(chainID sdk.ChainID) bool GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) } From 420d1ed250ae8d0dea9bdc40097919aeb92017b6 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 4 Jan 2023 18:57:02 +0800 Subject: [PATCH 25/50] fix error message --- x/oracle/types/msgs.go | 2 +- x/oracle/types/msgs_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index c93b442bfa..adb779a2ca 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -64,7 +64,7 @@ func (m *MsgClaim) ValidateBasic() error { if len(m.VoteAddressSet) != ValidatorBitSetLength { return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("length of vote addresse set should be %d", ValidatorBitSetLength)) + fmt.Sprintf("length of vote address set should be %d", ValidatorBitSetLength)) } if len(m.AggSignature) != BLSSignatureLength { diff --git a/x/oracle/types/msgs_test.go b/x/oracle/types/msgs_test.go index 608bad92b6..5d877a232a 100644 --- a/x/oracle/types/msgs_test.go +++ b/x/oracle/types/msgs_test.go @@ -104,7 +104,7 @@ func TestValidateBasic(t *testing.T) { AggSignature: []byte("test sig"), }, false, - fmt.Sprintf("length of vote addresse set should be %d", types.ValidatorBitSetLength), + fmt.Sprintf("length of vote address set should be %d", types.ValidatorBitSetLength), }, { types.MsgClaim{ From 6bc55634ebd9251d7d3a7aae9c40a840c7e6ce11 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 6 Jan 2023 15:23:17 +0800 Subject: [PATCH 26/50] rebase develop branch --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index d92fb93695..c551371198 100644 --- a/go.mod +++ b/go.mod @@ -58,8 +58,8 @@ require ( github.com/tendermint/tendermint v0.34.22 github.com/tendermint/tm-db v0.6.7 github.com/wealdtech/go-eth2-util v1.6.3 - golang.org/x/crypto v0.1.0 github.com/willf/bitset v1.1.3 + golang.org/x/crypto v0.1.0 golang.org/x/exp v0.0.0-20220722155223-a9213eeb770e golang.org/x/text v0.4.0 google.golang.org/genproto v0.0.0-20221014213838-99cd37c6964a From 19dcf0a90e1d52f273e0d46d80bb8595f24c168c Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 9 Jan 2023 15:23:21 +0800 Subject: [PATCH 27/50] refactor name of function ProcessClaim to CheckClaim --- x/oracle/keeper/keeper.go | 13 +++++++++---- x/oracle/keeper/keeper_test.go | 10 +++++----- x/oracle/keeper/msg_server.go | 2 +- x/oracle/types/errors.go | 3 ++- 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 051ec7c189..167ca820b0 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -74,16 +74,21 @@ func (k Keeper) GetRelayerParam(ctx sdk.Context) (uint64, uint64) { } func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { + fromAddress, err := sdk.AccAddressFromHexUnsafe(claim.FromAddress) + if err != nil { + return false, sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("from address (%s) is invalid", claim.FromAddress)) + } + var validatorIndex int64 = -1 for index, validator := range validators { - if validator.RelayerAddress == claim.FromAddress { + if validator.RelayerAddress == fromAddress.String() { validatorIndex = int64(index) break } } if validatorIndex < 0 { - return false, sdkerrors.Wrapf(types.ErrNotValidator, fmt.Sprintf("sender is not validator")) + return false, sdkerrors.Wrapf(types.ErrNotRelayer, fmt.Sprintf("sender(%s) is not a relayer", fromAddress.String())) } // check inturn validator index @@ -105,8 +110,8 @@ func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Val return uint64(validatorIndex) == (inturnValidatorIndex+backoffIndex)%uint64(len(validators)), nil } -// ProcessClaim checks the bls signature -func (k Keeper) ProcessClaim(ctx sdk.Context, claim *types.MsgClaim) error { +// CheckClaim checks the bls signature +func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { historicalInfo, ok := k.StakingKeeper.GetHistoricalInfo(ctx, ctx.BlockHeight()) if !ok { return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("get historical validators failed")) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index c54ad6fc54..c668fca5a6 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -105,12 +105,12 @@ func (s *TestSuite) TestProcessClaim() { msgClaim.AggSignature = blsSig s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err := s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + err := s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().Nil(err, "error should be nil") // not in turn s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp)+6, 0)) - err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "validator is not in turn") @@ -121,7 +121,7 @@ func (s *TestSuite) TestProcessClaim() { } msgClaim.VoteAddressSet = wrongValBitSet.Bytes() s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "number of validator set is larger than validators") @@ -131,7 +131,7 @@ func (s *TestSuite) TestProcessClaim() { wrongValBitSet.Set(uint(validatorMap[newValidators[1].RelayerAddress])) msgClaim.VoteAddressSet = wrongValBitSet.Bytes() s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "not enough validators voted") @@ -140,7 +140,7 @@ func (s *TestSuite) TestProcessClaim() { msgClaim.AggSignature = bytes.Repeat([]byte{2}, 96) s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.ProcessClaim(s.ctx, &msgClaim) + err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "BLS signature converts failed") } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index c05292ec1e..3e72d46553 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -49,7 +49,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", types.RelayPackagesChannelId, sequence)) } - err := k.oracleKeeper.ProcessClaim(ctx, req) + err := k.oracleKeeper.CheckClaim(ctx, req) if err != nil { return nil, err } diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index 71aa61c235..30ac76fe9f 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -13,8 +13,9 @@ var ( ErrBlsPubKey = sdkerrors.Register(ModuleName, 9, "public key is invalid") ErrBlsVotesNotEnough = sdkerrors.Register(ModuleName, 10, "bls votes is not enough") ErrInvalidBlsSignature = sdkerrors.Register(ModuleName, 11, "bls signature is invalid") - ErrNotValidator = sdkerrors.Register(ModuleName, 12, "sender is not validator") + ErrNotRelayer = sdkerrors.Register(ModuleName, 12, "sender is not a relayer") ErrValidatorNotInTurn = sdkerrors.Register(ModuleName, 13, "validator is not in turn") ErrInvalidDestChainId = sdkerrors.Register(ModuleName, 14, "dest chain id is invalid") ErrInvalidSrcChainId = sdkerrors.Register(ModuleName, 15, "src chain id is invalid") + ErrInvalidAddress = sdkerrors.Register(ModuleName, 16, "address is invalid") ) From 3137311916c7a23f9e36c1e148574a3876100ae1 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 9 Jan 2023 16:42:54 +0800 Subject: [PATCH 28/50] add geneis initialization for oracle module --- proto/cosmos/oracle/v1/genesis.proto | 13 ++ x/oracle/keeper/keeper.go | 5 + x/oracle/module.go | 19 +- x/oracle/types/genesis.go | 33 +++ x/oracle/types/genesis.pb.go | 322 +++++++++++++++++++++++++++ 5 files changed, 388 insertions(+), 4 deletions(-) create mode 100644 proto/cosmos/oracle/v1/genesis.proto create mode 100644 x/oracle/types/genesis.go create mode 100644 x/oracle/types/genesis.pb.go diff --git a/proto/cosmos/oracle/v1/genesis.proto b/proto/cosmos/oracle/v1/genesis.proto new file mode 100644 index 0000000000..537f45d3c6 --- /dev/null +++ b/proto/cosmos/oracle/v1/genesis.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package cosmos.oracle.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; + +import "gogoproto/gogo.proto"; +import "cosmos/oracle/v1/oracle.proto"; + +// GenesisState defines the oracle module's genesis state. +message GenesisState { + // params defines all the parameters of related to oracle module. + Params params = 1 [(gogoproto.nullable) = false]; +} diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 167ca820b0..32f206e34d 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -59,6 +59,11 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } +func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { + k.Logger(ctx).Info("set oracle genesis state", "params", state.Params.String()) + k.SetParams(ctx, state.Params) +} + // SetParams sets the params of oarcle module func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) diff --git a/x/oracle/module.go b/x/oracle/module.go index 06d50346a3..2fc1613b78 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -2,6 +2,7 @@ package oracle import ( "encoding/json" + "fmt" "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -40,11 +41,18 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { // DefaultGenesis returns default genesis state as raw bytes for the params // module. -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return nil } +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} // ValidateGenesis performs genesis state validation for the params module. -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { - return nil +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. @@ -82,7 +90,10 @@ func NewAppModule(k keeper.Keeper) AppModule { func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // InitGenesis performs a no-op. -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + cdc.MustUnmarshalJSON(data, &genesisState) + am.keeper.InitGenesis(ctx, &genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/oracle/types/genesis.go b/x/oracle/types/genesis.go new file mode 100644 index 0000000000..b9a9217123 --- /dev/null +++ b/x/oracle/types/genesis.go @@ -0,0 +1,33 @@ +package types + +import ( + "fmt" +) + +// NewGenesisState creates a new GenesisState object +func NewGenesisState( + params Params, +) *GenesisState { + return &GenesisState{ + Params: params, + } +} + +// DefaultGenesisState - default GenesisState used by Cosmos Hub +func DefaultGenesisState() *GenesisState { + return &GenesisState{ + Params: DefaultParams(), + } +} + +// ValidateGenesis validates the slashing genesis parameters +func ValidateGenesis(data GenesisState) error { + if data.Params.RelayerTimeout <= 0 { + return fmt.Errorf("relayer timeout should be positive, is %d", data.Params.RelayerTimeout) + } + + if data.Params.RelayerBackoffTime <= 0 { + return fmt.Errorf("the relayer backoff time must be positive, is %d", data.Params.RelayerBackoffTime) + } + return nil +} diff --git a/x/oracle/types/genesis.pb.go b/x/oracle/types/genesis.pb.go new file mode 100644 index 0000000000..b3f165a83a --- /dev/null +++ b/x/oracle/types/genesis.pb.go @@ -0,0 +1,322 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/oracle/v1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + 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 + +// GenesisState defines the oracle module's genesis state. +type GenesisState struct { + // params defines all the parameters of related to oracle module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_46043ca9c8436fa3, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "cosmos.oracle.v1.GenesisState") +} + +func init() { proto.RegisterFile("cosmos/oracle/v1/genesis.proto", fileDescriptor_46043ca9c8436fa3) } + +var fileDescriptor_46043ca9c8436fa3 = []byte{ + // 196 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xce, 0x2f, 0xce, + 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x4f, 0x4f, 0xcd, + 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x80, 0xc8, 0xeb, 0x41, + 0xe4, 0xf5, 0xca, 0x0c, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x92, 0xfa, 0x20, 0x16, 0x44, + 0x9d, 0x94, 0x2c, 0x86, 0x39, 0x50, 0x1d, 0x60, 0x69, 0x25, 0x37, 0x2e, 0x1e, 0x77, 0x88, 0xb9, + 0xc1, 0x25, 0x89, 0x25, 0xa9, 0x42, 0x66, 0x5c, 0x6c, 0x05, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x12, + 0x8c, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0x12, 0x7a, 0xe8, 0xf6, 0xe8, 0x05, 0x80, 0xe5, 0x9d, 0x58, + 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x82, 0xaa, 0x76, 0x72, 0x3d, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, + 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, + 0x63, 0x39, 0x86, 0x28, 0xed, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, + 0xa8, 0x5b, 0x20, 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, 0x05, 0xcc, 0x61, 0x25, 0x95, 0x05, 0xa9, + 0xc5, 0x49, 0x6c, 0x60, 0x57, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xee, 0x58, 0x23, 0xac, + 0xfe, 0x00, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) From b3469b1c36b1be38a5a565fbe151db2df77dadfc Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 9 Jan 2023 17:19:00 +0800 Subject: [PATCH 29/50] add geneis initialization for cross chain module --- proto/cosmos/crosschain/v1/genesis.proto | 13 + x/crosschain/keeper/keeper.go | 6 + x/crosschain/module.go | 19 +- x/crosschain/types/genesis.go | 38 +++ x/crosschain/types/genesis.pb.go | 324 +++++++++++++++++++++++ x/crosschain/types/params.go | 2 +- x/oracle/keeper/keeper.go | 1 + x/oracle/types/genesis.go | 2 +- 8 files changed, 399 insertions(+), 6 deletions(-) create mode 100644 proto/cosmos/crosschain/v1/genesis.proto create mode 100644 x/crosschain/types/genesis.go create mode 100644 x/crosschain/types/genesis.pb.go diff --git a/proto/cosmos/crosschain/v1/genesis.proto b/proto/cosmos/crosschain/v1/genesis.proto new file mode 100644 index 0000000000..5b485acb8b --- /dev/null +++ b/proto/cosmos/crosschain/v1/genesis.proto @@ -0,0 +1,13 @@ +syntax = "proto3"; +package cosmos.crosschain.v1; + +option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; + +import "gogoproto/gogo.proto"; +import "cosmos/crosschain/v1/crosschain.proto"; + +// GenesisState defines the oracle module's genesis state. +message GenesisState { + // params defines all the parameters of related to oracle module. + Params params = 1 [(gogoproto.nullable) = false]; +} diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 8dd0ccdcb0..bc5b27c8c8 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -45,6 +45,12 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } +// InitGenesis inits the genesis state of cross chain module +func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { + k.Logger(ctx).Info("set cross chain genesis state", "params", state.Params.String()) + k.SetParams(ctx, state.Params) +} + // GetRelayerFeeParam returns the default relayer fee for cross chain tx func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { var relayerFeeParam string diff --git a/x/crosschain/module.go b/x/crosschain/module.go index 5dc0501a91..4cdf0f85b7 100644 --- a/x/crosschain/module.go +++ b/x/crosschain/module.go @@ -3,6 +3,7 @@ package crosschain import ( "context" "encoding/json" + "fmt" "math/rand" "github.com/grpc-ecosystem/grpc-gateway/runtime" @@ -39,11 +40,18 @@ func (AppModuleBasic) RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) {} // DefaultGenesis returns default genesis state as raw bytes for the params // module. -func (AppModuleBasic) DefaultGenesis(_ codec.JSONCodec) json.RawMessage { return nil } +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONCodec) json.RawMessage { + return cdc.MustMarshalJSON(types.DefaultGenesisState()) +} // ValidateGenesis performs genesis state validation for the params module. -func (AppModuleBasic) ValidateGenesis(_ codec.JSONCodec, config client.TxEncodingConfig, _ json.RawMessage) error { - return nil +func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncodingConfig, bz json.RawMessage) error { + var data types.GenesisState + if err := cdc.UnmarshalJSON(bz, &data); err != nil { + return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err) + } + + return types.ValidateGenesis(data) } // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. @@ -81,7 +89,10 @@ func NewAppModule(k keeper.Keeper) AppModule { func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} // InitGenesis performs a no-op. -func (am AppModule) InitGenesis(_ sdk.Context, _ codec.JSONCodec, _ json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { + var genesisState types.GenesisState + cdc.MustUnmarshalJSON(data, &genesisState) + am.keeper.InitGenesis(ctx, &genesisState) return []abci.ValidatorUpdate{} } diff --git a/x/crosschain/types/genesis.go b/x/crosschain/types/genesis.go new file mode 100644 index 0000000000..1f418457fa --- /dev/null +++ b/x/crosschain/types/genesis.go @@ -0,0 +1,38 @@ +package types + +import ( + "fmt" + "math/big" +) + +// NewGenesisState creates a new GenesisState object +func NewGenesisState( + params Params, +) *GenesisState { + return &GenesisState{ + Params: params, + } +} + +// DefaultGenesisState - default GenesisState +func DefaultGenesisState() *GenesisState { + return &GenesisState{ + Params: DefaultParams(), + } +} + +// ValidateGenesis validates the slashing genesis parameters +func ValidateGenesis(data GenesisState) error { + relayerFee := big.NewInt(0) + relayerFee, valid := relayerFee.SetString(data.Params.RelayerFee, 10) + + if !valid { + return fmt.Errorf("invalid relayer fee, is %s", data.Params.RelayerFee) + } + + if relayerFee.Cmp(big.NewInt(0)) < 0 { + return fmt.Errorf("relayer fee should not be negative, is %s", data.Params.RelayerFee) + } + + return nil +} diff --git a/x/crosschain/types/genesis.pb.go b/x/crosschain/types/genesis.pb.go new file mode 100644 index 0000000000..18d1f2d0f6 --- /dev/null +++ b/x/crosschain/types/genesis.pb.go @@ -0,0 +1,324 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: cosmos/crosschain/v1/genesis.proto + +package types + +import ( + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + 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 + +// GenesisState defines the oracle module's genesis state. +type GenesisState struct { + // params defines all the parameters of related to oracle module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_810ffca0c738aa54, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "cosmos.crosschain.v1.GenesisState") +} + +func init() { + proto.RegisterFile("cosmos/crosschain/v1/genesis.proto", fileDescriptor_810ffca0c738aa54) +} + +var fileDescriptor_810ffca0c738aa54 = []byte{ + // 201 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, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, + 0xd4, 0x4f, 0x4f, 0xcd, 0x4b, 0x2d, 0xce, 0x2c, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, + 0x81, 0xa8, 0xd1, 0x43, 0xa8, 0xd1, 0x2b, 0x33, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, + 0xd0, 0x07, 0xb1, 0x20, 0x6a, 0xa5, 0x54, 0xb1, 0x9a, 0x87, 0xa4, 0x13, 0xac, 0x4c, 0xc9, 0x8b, + 0x8b, 0xc7, 0x1d, 0x62, 0x47, 0x70, 0x49, 0x62, 0x49, 0xaa, 0x90, 0x15, 0x17, 0x5b, 0x41, 0x62, + 0x51, 0x62, 0x6e, 0xb1, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x8c, 0x1e, 0x36, 0x3b, 0xf5, + 0x02, 0xc0, 0x6a, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, 0x08, 0x82, 0xea, 0x70, 0xf2, 0x3c, 0xf1, + 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, 0x63, 0xb8, + 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xfd, 0xf4, 0xcc, 0x92, 0x8c, 0xd2, 0x24, + 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0x98, 0xbb, 0xc0, 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, 0x05, 0xb2, + 0x23, 0x4b, 0x2a, 0x0b, 0x52, 0x8b, 0x93, 0xd8, 0xc0, 0xae, 0x33, 0x06, 0x04, 0x00, 0x00, 0xff, + 0xff, 0xdd, 0xc4, 0x01, 0xd0, 0x16, 0x01, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrIntOverflowGenesis + } + 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, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 150ca35fc7..96080d1e54 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -8,7 +8,7 @@ import ( ) const ( - DefaultRelayerFeeParam string = "100000000" // TODO: tbd + DefaultRelayerFeeParam string = "1" ) var ( diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 32f206e34d..e9452fdb7a 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -59,6 +59,7 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", "x/"+types.ModuleName) } +// InitGenesis inits the genesis state of oracle module func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { k.Logger(ctx).Info("set oracle genesis state", "params", state.Params.String()) k.SetParams(ctx, state.Params) diff --git a/x/oracle/types/genesis.go b/x/oracle/types/genesis.go index b9a9217123..d0add40862 100644 --- a/x/oracle/types/genesis.go +++ b/x/oracle/types/genesis.go @@ -13,7 +13,7 @@ func NewGenesisState( } } -// DefaultGenesisState - default GenesisState used by Cosmos Hub +// DefaultGenesisState - default GenesisState func DefaultGenesisState() *GenesisState { return &GenesisState{ Params: DefaultParams(), From cbfeea58c281401b84a3652003680d34c6b9f1ec Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 9 Jan 2023 19:35:41 +0800 Subject: [PATCH 30/50] fix issue for getting relayer fee param --- x/crosschain/keeper/keeper.go | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index bc5b27c8c8..0f46b6ddae 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -52,14 +52,14 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { } // GetRelayerFeeParam returns the default relayer fee for cross chain tx -func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) (relayerFee *big.Int, err error) { +func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) *big.Int { var relayerFeeParam string k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) - relayerFee, valid := relayerFee.SetString(relayerFeeParam, 10) + relayerFee, valid := big.NewInt(0).SetString(relayerFeeParam, 10) if !valid { - return nil, fmt.Errorf("invalid relayer fee: %s", relayerFeeParam) + panic(fmt.Errorf("invalid relayer fee: %s", relayerFeeParam)) } - return relayerFee, nil + return relayerFee } // SetParams sets the params of cross chain module @@ -71,10 +71,7 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) { - relayerFee, err := k.GetRelayerFeeParam(ctx) - if err != nil { - return 0, fmt.Errorf("fail to load relayerFee, %v", err) - } + relayerFee := k.GetRelayerFeeParam(ctx) return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) } From d58e4b974f7f28fee50dc654194ba65d81da8fc4 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 9 Jan 2023 20:12:45 +0800 Subject: [PATCH 31/50] remove unused metrics --- x/oracle/keeper/keeper.go | 4 ---- x/oracle/keeper/msg_server.go | 2 -- x/oracle/metrics/metrics.go | 31 ------------------------------- 3 files changed, 37 deletions(-) delete mode 100644 x/oracle/metrics/metrics.go diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index e9452fdb7a..98baa692bd 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -12,7 +12,6 @@ import ( storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" - "github.com/cosmos/cosmos-sdk/x/oracle/metrics" "github.com/cosmos/cosmos-sdk/x/oracle/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -26,7 +25,6 @@ type Keeper struct { StakingKeeper types.StakingKeeper CrossChainKeeper types.CrossChainKeeper BankKeeper types.BankKeeper - Metrics *metrics.Metrics feeCollectorName string // name of the FeeCollector ModuleAccount } @@ -49,8 +47,6 @@ func NewKeeper( CrossChainKeeper: crossChainKeeper, BankKeeper: bankKeeper, StakingKeeper: stakingKeeper, - - Metrics: metrics.PrometheusMetrics(), } } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 3e72d46553..155886a869 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -118,8 +118,6 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageType, &relayFee) if result.IsOk() { write() - } else { - oracleKeeper.Metrics.ErrNumOfChannels.With("channel_id", fmt.Sprintf("%d", pack.ChannelId)).Add(1) } // write ack package diff --git a/x/oracle/metrics/metrics.go b/x/oracle/metrics/metrics.go deleted file mode 100644 index f0f649ab8d..0000000000 --- a/x/oracle/metrics/metrics.go +++ /dev/null @@ -1,31 +0,0 @@ -package metrics - -import ( - metricsPkg "github.com/go-kit/kit/metrics" - "github.com/go-kit/kit/metrics/discard" - "github.com/go-kit/kit/metrics/prometheus" - stdprometheus "github.com/prometheus/client_golang/prometheus" -) - -// Metrics contains Metrics exposed by this package. -type Metrics struct { - ErrNumOfChannels metricsPkg.Counter -} - -// PrometheusMetrics returns Metrics build using Prometheus client library. -func PrometheusMetrics() *Metrics { - return &Metrics{ - ErrNumOfChannels: prometheus.NewCounterFrom(stdprometheus.CounterOpts{ - Subsystem: "oracle", - Name: "err_num_of_channels", - Help: "The error numbers of channel happened from boot", - }, []string{"channel_id"}), - } -} - -// NopMetrics returns no-op Metrics. -func NopMetrics() *Metrics { - return &Metrics{ - ErrNumOfChannels: discard.NewCounter(), - } -} From 626b6321cf9e5b68e09b63c6066d158ff66da2f6 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 14:08:14 +0800 Subject: [PATCH 32/50] fix some comments and lint errors --- bsc/rlp/decode.go | 12 +- bsc/rlp/decode_test.go | 8 +- bsc/rlp/doc.go | 130 ------------------ bsc/rlp/encode.go | 4 +- proto/cosmos/crosschain/v1/crosschain.proto | 3 - proto/cosmos/crosschain/v1/event.proto | 3 +- proto/cosmos/oracle/v1/event.proto | 19 +-- proto/cosmos/oracle/v1/oracle.proto | 3 - proto/cosmos/oracle/v1/query.proto | 3 - types/cross_chain.go | 7 +- types/hex.go | 73 ---------- types/keccak256.go | 26 ++++ types/{hex_test.go => keccak256_test.go} | 0 types/tokens.go | 7 - x/crosschain/keeper/keeper.go | 8 +- x/crosschain/types/crosschain.pb.go | 21 ++- x/crosschain/types/event.pb.go | 42 +++--- x/crosschain/types/params.go | 4 +- x/gashub/keeper/grpc_query_test.go | 1 + x/oracle/keeper/keeper.go | 6 +- x/oracle/keeper/keeper_test.go | 3 +- x/oracle/keeper/msg_server.go | 33 ++--- x/oracle/keeper/msg_server_test.go | 3 +- x/oracle/keeper/querier.go | 1 - x/oracle/module.go | 1 - x/oracle/testutil/bls.go | 10 +- x/oracle/types/codec.go | 2 +- x/oracle/types/event.pb.go | 140 ++++++++++++-------- x/oracle/types/expected_keepers.go | 4 +- x/oracle/types/msgs.go | 12 +- x/oracle/types/oracle.pb.go | 26 ++-- x/oracle/types/query.pb.go | 18 +-- 32 files changed, 224 insertions(+), 409 deletions(-) delete mode 100644 bsc/rlp/doc.go delete mode 100644 types/hex.go create mode 100644 types/keccak256.go rename types/{hex_test.go => keccak256_test.go} (100%) delete mode 100644 types/tokens.go diff --git a/bsc/rlp/decode.go b/bsc/rlp/decode.go index 5f3f5eedfd..df70ead2d1 100644 --- a/bsc/rlp/decode.go +++ b/bsc/rlp/decode.go @@ -33,7 +33,7 @@ import ( // EOL is returned when the end of the current list // has been reached during streaming. -var EOL = errors.New("rlp: end of list") +var EOL = errors.New("rlp: end of list") //nolint:all var ( ErrExpectedString = errors.New("rlp: expected String or Byte") @@ -65,16 +65,6 @@ type Decoder interface { DecodeRLP(*Stream) error } -// Decode parses RLP-encoded data from r and stores the result in the value pointed to by -// val. Please see package-level documentation for the decoding rules. Val must be a -// non-nil pointer. -// -// If r does not implement ByteReader, Decode will do its own buffering. -// -// Note that Decode does not set an input limit for all readers and may be vulnerable to -// panics cause by huge value sizes. If you need an input limit, use -// -// NewStream(r, limit).Decode(val) func Decode(r io.Reader, val interface{}) error { stream := streamPool.Get().(*Stream) defer streamPool.Put(stream) diff --git a/bsc/rlp/decode_test.go b/bsc/rlp/decode_test.go index 167e9974b9..caf831a902 100644 --- a/bsc/rlp/decode_test.go +++ b/bsc/rlp/decode_test.go @@ -369,11 +369,9 @@ type intField struct { X int } -var ( - veryBigInt = big.NewInt(0).Add( - big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), - big.NewInt(0xFFFF), - ) +var veryBigInt = big.NewInt(0).Add( + big.NewInt(0).Lsh(big.NewInt(0xFFFFFFFFFFFFFF), 16), + big.NewInt(0xFFFF), ) type hasIgnoredField struct { diff --git a/bsc/rlp/doc.go b/bsc/rlp/doc.go deleted file mode 100644 index 7e6ee85200..0000000000 --- a/bsc/rlp/doc.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2014 The go-ethereum Authors -// This file is part of the go-ethereum library. -// -// The go-ethereum library is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// The go-ethereum library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with the go-ethereum library. If not, see . - -/* -Package rlp implements the RLP serialization format. - -The purpose of RLP (Recursive Linear Prefix) is to encode arbitrarily nested arrays of -binary data, and RLP is the main encoding method used to serialize objects in Ethereum. -The only purpose of RLP is to encode structure; encoding specific atomic data types (eg. -strings, ints, floats) is left up to higher-order protocols. In Ethereum integers must be -represented in big endian binary form with no leading zeroes (thus making the integer -value zero equivalent to the empty string). - -RLP values are distinguished by a type tag. The type tag precedes the value in the input -stream and defines the size and kind of the bytes that follow. - - -Encoding Rules - -Package rlp uses reflection and encodes RLP based on the Go type of the value. - -If the type implements the Encoder interface, Encode calls EncodeRLP. It does not -call EncodeRLP on nil pointer values. - -To encode a pointer, the value being pointed to is encoded. A nil pointer to a struct -type, slice or array always encodes as an empty RLP list unless the slice or array has -elememt type byte. A nil pointer to any other value encodes as the empty string. - -Struct values are encoded as an RLP list of all their encoded public fields. Recursive -struct types are supported. - -To encode slices and arrays, the elements are encoded as an RLP list of the value's -elements. Note that arrays and slices with element type uint8 or byte are always encoded -as an RLP string. - -A Go string is encoded as an RLP string. - -An unsigned integer value is encoded as an RLP string. Zero always encodes as an empty RLP -string. big.Int values are treated as integers. Signed integers (int, int8, int16, ...) -are not supported and will return an error when encoding. - -Boolean values are encoded as the unsigned integers zero (false) and one (true). - -An interface value encodes as the value contained in the interface. - -Floating point numbers, maps, channels and functions are not supported. - - -Decoding Rules - -Decoding uses the following type-dependent rules: - -If the type implements the Decoder interface, DecodeRLP is called. - -To decode into a pointer, the value will be decoded as the element type of the pointer. If -the pointer is nil, a new value of the pointer's element type is allocated. If the pointer -is non-nil, the existing value will be reused. Note that package rlp never leaves a -pointer-type struct field as nil unless one of the "nil" struct tags is present. - -To decode into a struct, decoding expects the input to be an RLP list. The decoded -elements of the list are assigned to each public field in the order given by the struct's -definition. The input list must contain an element for each decoded field. Decoding -returns an error if there are too few or too many elements for the struct. - -To decode into a slice, the input must be a list and the resulting slice will contain the -input elements in order. For byte slices, the input must be an RLP string. Array types -decode similarly, with the additional restriction that the number of input elements (or -bytes) must match the array's defined length. - -To decode into a Go string, the input must be an RLP string. The input bytes are taken -as-is and will not necessarily be valid UTF-8. - -To decode into an unsigned integer type, the input must also be an RLP string. The bytes -are interpreted as a big endian representation of the integer. If the RLP string is larger -than the bit size of the type, decoding will return an error. Decode also supports -*big.Int. There is no size limit for big integers. - -To decode into a boolean, the input must contain an unsigned integer of value zero (false) -or one (true). - -To decode into an interface value, one of these types is stored in the value: - - []interface{}, for RLP lists - []byte, for RLP strings - -Non-empty interface types are not supported when decoding. -Signed integers, floating point numbers, maps, channels and functions cannot be decoded into. - - -Struct Tags - -Package rlp honours certain struct tags: "-", "tail", "nil", "nilList" and "nilString". - -The "-" tag ignores fields. - -The "tail" tag, which may only be used on the last exported struct field, allows slurping -up any excess list elements into a slice. See examples for more details. - -The "nil" tag applies to pointer-typed fields and changes the decoding rules for the field -such that input values of size zero decode as a nil pointer. This tag can be useful when -decoding recursive types. - - type StructWithOptionalFoo struct { - Foo *[20]byte `rlp:"nil"` - } - -RLP supports two kinds of empty values: empty lists and empty strings. When using the -"nil" tag, the kind of empty value allowed for a type is chosen automatically. A struct -field whose Go type is a pointer to an unsigned integer, string, boolean or byte -array/slice expects an empty RLP string. Any other pointer field type encodes/decodes as -an empty RLP list. - -The choice of null value can be made explicit with the "nilList" and "nilString" struct -tags. Using these tags encodes/decodes a Go nil pointer value as the kind of empty -RLP value defined by the tag. -*/ -package rlp diff --git a/bsc/rlp/encode.go b/bsc/rlp/encode.go index 9c9e8d706d..d6e5a73393 100644 --- a/bsc/rlp/encode.go +++ b/bsc/rlp/encode.go @@ -360,7 +360,7 @@ func writeRawValue(val reflect.Value, w *encbuf) error { func writeUint(val reflect.Value, w *encbuf) error { i := val.Uint() - if i == 0 { + if i == 0 { //nolint:all w.str = append(w.str, 0x80) } else if i < 128 { // fits single byte @@ -398,7 +398,7 @@ func writeBigIntNoPtr(val reflect.Value, w *encbuf) error { } func writeBigInt(i *big.Int, w *encbuf) error { - if cmp := i.Cmp(big0); cmp == -1 { + if cmp := i.Cmp(big0); cmp == -1 { //nolint:all return fmt.Errorf("rlp: cannot encode negative *big.Int") } else if cmp == 0 { w.str = append(w.str, 0x80) diff --git a/proto/cosmos/crosschain/v1/crosschain.proto b/proto/cosmos/crosschain/v1/crosschain.proto index 8508864dba..fab7080458 100644 --- a/proto/cosmos/crosschain/v1/crosschain.proto +++ b/proto/cosmos/crosschain/v1/crosschain.proto @@ -3,9 +3,6 @@ package cosmos.crosschain.v1; option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; - // Params holds parameters for the cross chain module. message Params { string relayer_fee = 1; diff --git a/proto/cosmos/crosschain/v1/event.proto b/proto/cosmos/crosschain/v1/event.proto index 11a695088a..eae3023011 100644 --- a/proto/cosmos/crosschain/v1/event.proto +++ b/proto/cosmos/crosschain/v1/event.proto @@ -2,10 +2,9 @@ syntax = "proto3"; package cosmos.crosschain.v1; -import "cosmos_proto/cosmos.proto"; - option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; +// EventCrossChain is emitted when there is a cross chain package created message EventCrossChain { uint32 src_chain_id = 1; uint32 dest_chain_id = 2; diff --git a/proto/cosmos/oracle/v1/event.proto b/proto/cosmos/oracle/v1/event.proto index ce40f03749..733ee975dc 100644 --- a/proto/cosmos/oracle/v1/event.proto +++ b/proto/cosmos/oracle/v1/event.proto @@ -2,17 +2,18 @@ syntax = "proto3"; package cosmos.oracle.v1; -import "cosmos_proto/cosmos.proto"; option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; +// EventPackageClaim is emitted when a cross chain package is processed message EventPackageClaim { - uint32 chain_id = 1; - uint32 channel_id = 2; - uint32 package_type = 3; - uint64 receive_sequence = 4; - int64 send_sequence = 5; - bool crash = 6; - string error_msg = 7; - string relay_fee = 8; + uint32 src_chain_id = 1; + uint32 dest_chain_id = 2; + uint32 channel_id = 3; + uint32 package_type = 4; + uint64 receive_sequence = 5; + int64 send_sequence = 6; + bool crash = 7; + string error_msg = 8; + string relay_fee = 9; } \ No newline at end of file diff --git a/proto/cosmos/oracle/v1/oracle.proto b/proto/cosmos/oracle/v1/oracle.proto index f406f2e768..cb2d9851e5 100644 --- a/proto/cosmos/oracle/v1/oracle.proto +++ b/proto/cosmos/oracle/v1/oracle.proto @@ -3,9 +3,6 @@ package cosmos.oracle.v1; option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; -import "gogoproto/gogo.proto"; -import "cosmos_proto/cosmos.proto"; - // Params holds parameters for the oracle module. message Params { uint64 relayer_timeout = 1; // in s diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto index 1915d0295d..22f9c63aaf 100644 --- a/proto/cosmos/oracle/v1/query.proto +++ b/proto/cosmos/oracle/v1/query.proto @@ -1,9 +1,6 @@ syntax = "proto3"; package cosmos.oracle.v1; -import "gogoproto/gogo.proto"; -import "google/api/annotations.proto"; - option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; // Query provides defines the gRPC querier service. diff --git a/types/cross_chain.go b/types/cross_chain.go index 28a6312207..b12b48e852 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -10,8 +10,10 @@ import ( type CrossChainPackageType uint8 -type ChannelID uint8 -type ChainID uint16 +type ( + ChannelID uint8 + ChainID uint16 +) const ( SynCrossChainPackageType CrossChainPackageType = 0x00 @@ -59,7 +61,6 @@ type CrossChainApplication interface { ExecuteFailAckPackage(ctx Context, payload []byte) ExecuteResult } -// TODO: define the execute result type ExecuteResult struct { Err error Payload []byte diff --git a/types/hex.go b/types/hex.go deleted file mode 100644 index f460f7a922..0000000000 --- a/types/hex.go +++ /dev/null @@ -1,73 +0,0 @@ -package types - -import ( - "encoding/hex" - "errors" - - "github.com/ethereum/go-ethereum/common" - "golang.org/x/crypto/sha3" -) - -func HexAddress(a []byte) string { - if len(a) == 0 { - return "" - } - unchecksummed := hex.EncodeToString(a[:]) - sha := sha3.NewLegacyKeccak256() - sha.Write([]byte(unchecksummed)) - hash := sha.Sum(nil) - - result := []byte(unchecksummed) - for i := 0; i < len(result); i++ { - hashByte := hash[i/2] - if i%2 == 0 { - hashByte = hashByte >> 4 - } else { - hashByte &= 0xf - } - if result[i] > '9' && hashByte > 7 { - result[i] -= 32 - } - } - return "0x" + string(result) -} - -func HexEncode(b []byte) string { - enc := make([]byte, len(b)*2+2) - copy(enc, "0x") - hex.Encode(enc[2:], b) - return string(enc) -} - -// Decode decodes a hex string with 0x prefix. -func HexDecode(input string) ([]byte, error) { - if !Has0xPrefix(input) { - return nil, errors.New("hex string must have 0x prefix") - } - return hex.DecodeString(input[2:]) -} - -// has0xPrefix validates str begins with '0x' or '0X'. -func Has0xPrefix(input string) bool { - return len(input) >= 2 && input[0] == '0' && (input[1] == 'x' || input[1] == 'X') -} - -// Keccak256 calculates and returns the Keccak256 hash of the input data. -func Keccak256(data ...[]byte) []byte { - d := sha3.NewLegacyKeccak256() - for _, b := range data { - d.Write(b) - } - return d.Sum(nil) -} - -// Keccak256Hash calculates and returns the Keccak256 hash of the input data, -// converting it to an internal Hash data structure. -func Keccak256Hash(data ...[]byte) (h common.Hash) { - d := sha3.NewLegacyKeccak256() - for _, b := range data { - d.Write(b) - } - d.Sum(h[:0]) - return h -} diff --git a/types/keccak256.go b/types/keccak256.go new file mode 100644 index 0000000000..094d2b8ee9 --- /dev/null +++ b/types/keccak256.go @@ -0,0 +1,26 @@ +package types + +import ( + "github.com/ethereum/go-ethereum/common" + "golang.org/x/crypto/sha3" +) + +// Keccak256 calculates and returns the Keccak256 hash of the input data. +func Keccak256(data ...[]byte) []byte { + d := sha3.NewLegacyKeccak256() + for _, b := range data { + d.Write(b) + } + return d.Sum(nil) +} + +// Keccak256Hash calculates and returns the Keccak256 hash of the input data, +// converting it to an internal Hash data structure. +func Keccak256Hash(data ...[]byte) (h common.Hash) { + d := sha3.NewLegacyKeccak256() + for _, b := range data { + d.Write(b) + } + d.Sum(h[:0]) + return h +} diff --git a/types/hex_test.go b/types/keccak256_test.go similarity index 100% rename from types/hex_test.go rename to types/keccak256_test.go diff --git a/types/tokens.go b/types/tokens.go deleted file mode 100644 index eea072c863..0000000000 --- a/types/tokens.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -const ( - NativeTokenSymbol = "BNB" - - TokenMaxTotalSupply int64 = 9000000000000000000 // 90 billions with 8 decimal digits -) diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 0f46b6ddae..c7064b9510 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -69,8 +69,8 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { // CreateRawIBCPackage creates a cross chain package with default cross chain fee func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) { - + packageType sdk.CrossChainPackageType, packageLoad []byte, +) (uint64, error) { relayerFee := k.GetRelayerFeeParam(ctx) return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) @@ -78,8 +78,8 @@ func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, ch // CreateRawIBCPackageWithFee creates a cross chain package with given cross chain fee func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int) (uint64, error) { - + packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int, +) (uint64, error) { if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, destChainID, channelID) != sdk.ChannelAllow { return 0, fmt.Errorf("channel %d is not allowed to write syn package", channelID) } diff --git a/x/crosschain/types/crosschain.pb.go b/x/crosschain/types/crosschain.pb.go index 76e0c8da43..445f7aded3 100644 --- a/x/crosschain/types/crosschain.pb.go +++ b/x/crosschain/types/crosschain.pb.go @@ -5,8 +5,6 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" @@ -78,19 +76,18 @@ func init() { } var fileDescriptor_d7b94a7254cf916a = []byte{ - // 187 bytes of a gzipped FileDescriptorProto + // 164 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, 0x44, 0xe2, 0xe9, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x89, 0x40, 0x94, 0xe9, 0x21, 0x49, 0x94, - 0x19, 0x4a, 0x89, 0xa4, 0xe7, 0xa7, 0xe7, 0x83, 0x15, 0xe8, 0x83, 0x58, 0x10, 0xb5, 0x52, 0x92, - 0x10, 0xb5, 0xf1, 0x10, 0x09, 0xa8, 0x46, 0x30, 0x47, 0x49, 0x93, 0x8b, 0x2d, 0x20, 0xb1, 0x28, - 0x31, 0xb7, 0x58, 0x48, 0x9e, 0x8b, 0xbb, 0x28, 0x35, 0x27, 0xb1, 0x32, 0xb5, 0x28, 0x3e, 0x2d, - 0x35, 0x55, 0x82, 0x51, 0x81, 0x51, 0x83, 0x33, 0x88, 0x0b, 0x2a, 0xe4, 0x96, 0x9a, 0xea, 0xe4, - 0x79, 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, 0xfa, 0xe9, 0x99, 0x25, 0x19, - 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0x30, 0xd7, 0x83, 0x29, 0xdd, 0xe2, 0x94, 0x6c, 0xfd, - 0x0a, 0x64, 0xaf, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x27, 0xb1, 0x81, 0x2d, 0x37, 0x06, 0x04, 0x00, - 0x00, 0xff, 0xff, 0xcc, 0x3a, 0x09, 0xdd, 0xec, 0x00, 0x00, 0x00, + 0x19, 0x2a, 0x69, 0x72, 0xb1, 0x05, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x0b, 0xc9, 0x73, 0x71, 0x17, + 0xa5, 0xe6, 0x24, 0x56, 0xa6, 0x16, 0xc5, 0xa7, 0xa5, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, + 0x06, 0x71, 0x41, 0x85, 0xdc, 0x52, 0x53, 0x9d, 0x3c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, + 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, + 0x58, 0x8e, 0x21, 0x4a, 0x3f, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, + 0xe6, 0x18, 0x30, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0xec, 0xb2, 0x92, 0xca, 0x82, 0xd4, + 0xe2, 0x24, 0x36, 0xb0, 0x93, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x9a, 0x72, 0xe2, 0x66, + 0xbb, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/crosschain/types/event.pb.go b/x/crosschain/types/event.pb.go index 3abfacc51b..2ff60cd1d1 100644 --- a/x/crosschain/types/event.pb.go +++ b/x/crosschain/types/event.pb.go @@ -5,7 +5,6 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" proto "github.com/gogo/protobuf/proto" io "io" math "math" @@ -23,6 +22,7 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// EventCrossChain is emitted when there is a cross chain package created type EventCrossChain struct { SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` @@ -130,27 +130,27 @@ func init() { func init() { proto.RegisterFile("cosmos/crosschain/v1/event.proto", fileDescriptor_2a5a3ba75f5dd2c3) } var fileDescriptor_2a5a3ba75f5dd2c3 = []byte{ - // 320 bytes of a gzipped FileDescriptorProto + // 309 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xcd, 0x4e, 0x32, 0x31, - 0x14, 0x86, 0x29, 0x1f, 0x1f, 0xc2, 0x01, 0x62, 0xd2, 0xb8, 0x18, 0x89, 0x8e, 0x23, 0xab, 0xd9, - 0x38, 0x0d, 0xf1, 0x0e, 0x24, 0x9a, 0x90, 0xb8, 0x22, 0xae, 0xdc, 0x4c, 0x4a, 0x7b, 0x84, 0x09, - 0xcc, 0x74, 0x9c, 0x16, 0x22, 0x77, 0xe1, 0xce, 0x5b, 0x72, 0xc9, 0xd2, 0xa5, 0x81, 0x1b, 0x31, - 0x2d, 0xc3, 0xcf, 0xaa, 0x39, 0x4f, 0x9f, 0xf7, 0x4d, 0xd3, 0x03, 0x81, 0x50, 0x3a, 0x55, 0x9a, - 0x89, 0x42, 0x69, 0x2d, 0xa6, 0x3c, 0xc9, 0xd8, 0xb2, 0xcf, 0x70, 0x89, 0x99, 0x89, 0xf2, 0x42, - 0x19, 0x45, 0x2f, 0x76, 0x46, 0x74, 0x34, 0xa2, 0x65, 0xbf, 0x7b, 0xb9, 0xa3, 0xb1, 0x73, 0x58, - 0xa9, 0xb8, 0xa1, 0xf7, 0x55, 0x85, 0xf3, 0x47, 0x5b, 0x30, 0xb0, 0x89, 0x81, 0x4d, 0xd0, 0x00, - 0xda, 0xba, 0x10, 0xb1, 0x8b, 0xc7, 0x89, 0xf4, 0x48, 0x40, 0xc2, 0xce, 0x08, 0x74, 0x21, 0xdc, - 0xfd, 0x50, 0xd2, 0x1e, 0x74, 0x24, 0x6a, 0x73, 0x54, 0xaa, 0x4e, 0x69, 0x59, 0xb8, 0x77, 0xae, - 0x01, 0xc4, 0x94, 0x67, 0x19, 0xce, 0xad, 0xf0, 0xcf, 0x09, 0xcd, 0x92, 0x0c, 0x25, 0xed, 0x42, - 0x43, 0xe3, 0xfb, 0x02, 0x33, 0x81, 0x5e, 0x2d, 0x20, 0x61, 0x6d, 0x74, 0x98, 0xe9, 0x2d, 0xb4, - 0x73, 0x2e, 0x66, 0x7c, 0x82, 0xb1, 0x59, 0xe5, 0xe8, 0xfd, 0xdf, 0xb5, 0x97, 0xec, 0x65, 0x95, - 0x23, 0xbd, 0x82, 0xa6, 0x49, 0x52, 0xd4, 0x86, 0xa7, 0xb9, 0x57, 0x77, 0xf9, 0x23, 0x38, 0x2d, - 0x98, 0x2b, 0x2e, 0xbd, 0xb3, 0x80, 0x84, 0xed, 0x43, 0xc1, 0xb3, 0xe2, 0x92, 0xde, 0x40, 0xab, - 0xc0, 0x39, 0x5f, 0x61, 0x11, 0xbf, 0x21, 0x7a, 0x8d, 0x80, 0x84, 0xcd, 0x11, 0x94, 0xe8, 0x09, - 0xf1, 0x61, 0xf8, 0xbd, 0xf1, 0xc9, 0x7a, 0xe3, 0x93, 0xdf, 0x8d, 0x4f, 0x3e, 0xb7, 0x7e, 0x65, - 0xbd, 0xf5, 0x2b, 0x3f, 0x5b, 0xbf, 0xf2, 0xca, 0x26, 0x89, 0x99, 0x2e, 0xc6, 0x91, 0x50, 0x29, - 0xdb, 0x6f, 0xc4, 0x1d, 0x77, 0x5a, 0xce, 0xd8, 0xc7, 0xe9, 0x7a, 0xec, 0xf3, 0xf5, 0xb8, 0xee, - 0xfe, 0xfa, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0xd1, 0x33, 0xd1, 0x2c, 0xc0, 0x01, 0x00, 0x00, + 0x14, 0x86, 0x29, 0x1f, 0x1f, 0xc2, 0x01, 0x62, 0xd2, 0xb8, 0x98, 0x18, 0x1d, 0x47, 0x56, 0xb3, + 0x71, 0x1a, 0xe2, 0x1d, 0x48, 0x34, 0x21, 0x71, 0x45, 0x5c, 0xb9, 0x99, 0x94, 0xf6, 0x08, 0x13, + 0x98, 0xe9, 0xd8, 0x16, 0x22, 0x77, 0xe1, 0xce, 0x5b, 0x72, 0xc9, 0xd2, 0xa5, 0x81, 0x1b, 0x31, + 0x2d, 0xbf, 0xab, 0xa6, 0x4f, 0x9f, 0xbe, 0x39, 0x39, 0x2f, 0x44, 0x42, 0x99, 0x5c, 0x19, 0x26, + 0xb4, 0x32, 0x46, 0x4c, 0x78, 0x56, 0xb0, 0x45, 0x8f, 0xe1, 0x02, 0x0b, 0x9b, 0x94, 0x5a, 0x59, + 0x45, 0x2f, 0xb6, 0x46, 0x72, 0x34, 0x92, 0x45, 0xaf, 0xfb, 0x55, 0x85, 0xf3, 0x47, 0x67, 0xf5, + 0x1d, 0xee, 0x3b, 0x4c, 0x23, 0x68, 0x1b, 0x2d, 0x52, 0xef, 0xa4, 0x99, 0x0c, 0x48, 0x44, 0xe2, + 0xce, 0x10, 0x8c, 0x16, 0xfe, 0x7d, 0x20, 0x69, 0x17, 0x3a, 0x12, 0x8d, 0x3d, 0x2a, 0x55, 0xaf, + 0xb4, 0x1c, 0xdc, 0x3b, 0xd7, 0x00, 0x62, 0xc2, 0x8b, 0x02, 0x67, 0x4e, 0xf8, 0xe7, 0x85, 0xe6, + 0x8e, 0x0c, 0x24, 0xbd, 0x84, 0x86, 0xc1, 0xf7, 0x39, 0x16, 0x02, 0x83, 0x5a, 0x44, 0xe2, 0xda, + 0xf0, 0x70, 0xa7, 0xb7, 0xd0, 0x2e, 0xb9, 0x98, 0xf2, 0x31, 0xa6, 0x76, 0x59, 0x62, 0xf0, 0x7f, + 0x9b, 0xbe, 0x63, 0x2f, 0xcb, 0x12, 0xe9, 0x15, 0x34, 0x6d, 0x96, 0xa3, 0xb1, 0x3c, 0x2f, 0x83, + 0xba, 0xff, 0x7f, 0x04, 0xa7, 0x01, 0x33, 0xc5, 0x65, 0x70, 0x16, 0x91, 0xb8, 0x7d, 0x08, 0x78, + 0x56, 0x5c, 0xd2, 0x1b, 0x68, 0x69, 0x9c, 0xf1, 0x25, 0xea, 0xf4, 0x0d, 0x31, 0x68, 0x44, 0x24, + 0x6e, 0x0e, 0x61, 0x87, 0x9e, 0x10, 0x1f, 0x06, 0xdf, 0xeb, 0x90, 0xac, 0xd6, 0x21, 0xf9, 0x5d, + 0x87, 0xe4, 0x73, 0x13, 0x56, 0x56, 0x9b, 0xb0, 0xf2, 0xb3, 0x09, 0x2b, 0xaf, 0x6c, 0x9c, 0xd9, + 0xc9, 0x7c, 0x94, 0x08, 0x95, 0xb3, 0xfd, 0xda, 0xfd, 0x71, 0x67, 0xe4, 0x94, 0x7d, 0x9c, 0x76, + 0xe0, 0xc6, 0x37, 0xa3, 0xba, 0x6f, 0xe0, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x98, 0x73, 0x1c, + 0xaf, 0xa5, 0x01, 0x00, 0x00, } func (m *EventCrossChain) Marshal() (dAtA []byte, err error) { diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 96080d1e54..7440cc7cfb 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -11,9 +11,7 @@ const ( DefaultRelayerFeeParam string = "1" ) -var ( - KeyParamRelayerFee = []byte("RelayerFee") -) +var KeyParamRelayerFee = []byte("RelayerFee") func DefaultParams() Params { return Params{ diff --git a/x/gashub/keeper/grpc_query_test.go b/x/gashub/keeper/grpc_query_test.go index b66e73ee50..d8987d6c2e 100644 --- a/x/gashub/keeper/grpc_query_test.go +++ b/x/gashub/keeper/grpc_query_test.go @@ -2,6 +2,7 @@ package keeper_test import ( gocontext "context" + "github.com/cosmos/cosmos-sdk/x/gashub/types" ) diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 98baa692bd..cce1c7605e 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -75,7 +75,8 @@ func (k Keeper) GetRelayerParam(ctx sdk.Context) (uint64, uint64) { return relayerTimeoutParam, relayerBackoffTimeParam } -func (k Keeper) IsValidatorInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { +// IsRelayerInturn checks the inturn status of the relayer +func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { fromAddress, err := sdk.AccAddressFromHexUnsafe(claim.FromAddress) if err != nil { return false, sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("from address (%s) is invalid", claim.FromAddress)) @@ -120,7 +121,7 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { } validators := historicalInfo.Valset - inturn, err := k.IsValidatorInturn(ctx, validators, claim) + inturn, err := k.IsRelayerInturn(ctx, validators, claim) if err != nil { return err } @@ -142,7 +143,6 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { votePubKey, err := bls.PublicKeyFromBytes(val.RelayerBlsKey) if err != nil { return sdkerrors.Wrapf(types.ErrBlsPubKey, fmt.Sprintf("BLS public key converts failed: %v", err)) - } votedPubKeys = append(votedPubKeys, votePubKey) } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index c668fca5a6..7a20723072 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -250,7 +250,7 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { for _, test := range tests { s.ctx = s.ctx.WithBlockTime(time.Unix(test.blockTime, 0)) - isInturn, err := s.app.OracleKeeper.IsValidatorInturn(s.ctx, vals, &test.claimMsg) + isInturn, err := s.app.OracleKeeper.IsRelayerInturn(s.ctx, vals, &test.claimMsg) if test.expectedPass { s.Require().Nil(err) @@ -259,7 +259,6 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { s.Require().False(isInturn) } } - } // Creates a new validators and asserts the error check. diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 155886a869..b5caeb88de 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -57,18 +57,20 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg packages := types.Packages{} err = rlp.DecodeBytes(req.Payload, &packages) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalidPayload, fmt.Sprintf("decode payload error")) + return nil, sdkerrors.Wrapf(types.ErrInvalidPayload, "decode payload error") } events := make([]proto.Message, 0, len(packages)) - for _, pack := range packages { + for idx := range packages { + pack := packages[idx] + event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) if err != nil { - // only do log, but let reset package get chance to execute. - logger.Error(fmt.Sprintf("process package failed, channel=%d, sequence=%d, error=%v", pack.ChannelId, pack.Sequence, err)) + // only do log, but let rest package get chance to execute. + logger.Error("process package failed", "channel", pack.ChannelId, "sequence", pack.Sequence, "error", err.Error()) return nil, err } - logger.Info(fmt.Sprintf("process package success, channel=%d, sequence=%d", pack.ChannelId, pack.Sequence)) + logger.Info("process package success", "channel", pack.ChannelId, "sequence", pack.Sequence) events = append(events, event) @@ -131,7 +133,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.PackageHeaderLength:]) } else { logger.Error("found payload without header", "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) - return nil, sdkerrors.Wrapf(types.ErrInvalidPackage, fmt.Sprintf("payload without header")) + return nil, sdkerrors.Wrapf(types.ErrInvalidPackage, "payload without header") } if ibcErr != nil { @@ -139,21 +141,20 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch return nil, ibcErr } sendSequence = int64(sendSeq) - } else { - if len(result.Payload) != 0 { - sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, - pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload) - if err != nil { - logger.Error("failed to write AckCrossChainPackage", "err", err) - return nil, err - } - sendSequence = int64(sendSeq) + } else if len(result.Payload) != 0 { + sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, + pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload) + if err != nil { + logger.Error("failed to write AckCrossChainPackage", "err", err) + return nil, err } + sendSequence = int64(sendSeq) } } claimEvent := &types.EventPackageClaim{ - ChainId: uint32(chainId), + SrcChainId: req.SrcChainId, + DestChainId: req.DestChainId, ChannelId: uint32(pack.ChannelId), PackageType: uint32(packageType), ReceiveSequence: pack.Sequence, diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index 10a41f6060..a3934b7292 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -13,8 +13,7 @@ import ( stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -type DummyCrossChainApp struct { -} +type DummyCrossChainApp struct{} func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, payload []byte, relayerFee *big.Int) sdk.ExecuteResult { return sdk.ExecuteResult{} diff --git a/x/oracle/keeper/querier.go b/x/oracle/keeper/querier.go index 6708edf7c7..9c80a39b3d 100644 --- a/x/oracle/keeper/querier.go +++ b/x/oracle/keeper/querier.go @@ -10,7 +10,6 @@ import ( func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { switch path[0] { - default: return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) } diff --git a/x/oracle/module.go b/x/oracle/module.go index 2fc1613b78..c6f206c541 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -57,7 +57,6 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, config client.TxEncod // RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the params module. func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *runtime.ServeMux) { - } // GetTxCmd returns no root tx command for the params module. diff --git a/x/oracle/testutil/bls.go b/x/oracle/testutil/bls.go index 318813345a..299e0feea6 100644 --- a/x/oracle/testutil/bls.go +++ b/x/oracle/testutil/bls.go @@ -17,16 +17,14 @@ type Vote struct { func (vote *Vote) Verify(eventHash []byte) error { blsPubKey, err := bls.PublicKeyFromBytes(vote.PubKey[:]) - if err != nil { return err } sig, err := bls.SignatureFromBytes(vote.Signature[:]) - if err != nil { return err } - if !sig.Verify(blsPubKey, eventHash[:]) { + if !sig.Verify(blsPubKey, eventHash) { return fmt.Errorf("verify sig error") } return nil @@ -64,9 +62,9 @@ func NewVoteSignerV2(privkey []byte) (*VoteSigner, error) { // SignVote sign a vote, data is used to signed to generate the signature func (signer *VoteSigner) SignVote(vote *Vote, data []byte) error { - signature := signer.privkey.Sign(data[:]) - copy(vote.PubKey[:], signer.pubKey.Marshal()[:]) - copy(vote.Signature[:], signature.Marshal()[:]) + signature := signer.privkey.Sign(data) + copy(vote.PubKey[:], signer.pubKey.Marshal()) + copy(vote.Signature[:], signature.Marshal()) return nil } diff --git a/x/oracle/types/codec.go b/x/oracle/types/codec.go index 39b5283ff6..44d5a265a9 100644 --- a/x/oracle/types/codec.go +++ b/x/oracle/types/codec.go @@ -13,7 +13,7 @@ import ( func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(&MsgClaim{}, "cosmos-sdk/MsgClaim", nil) - //legacy.RegisterAminoMsg(cdc, &MsgClaim{}, "cosmos-sdk/MsgClaim") + // legacy.RegisterAminoMsg(cdc, &MsgClaim{}, "cosmos-sdk/MsgClaim") // this line is used by starport scaffolding # 2 } diff --git a/x/oracle/types/event.pb.go b/x/oracle/types/event.pb.go index c296cee58c..0ac650ac15 100644 --- a/x/oracle/types/event.pb.go +++ b/x/oracle/types/event.pb.go @@ -5,7 +5,6 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" proto "github.com/gogo/protobuf/proto" io "io" math "math" @@ -23,15 +22,17 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// EventPackageClaim is emitted when a cross chain package is processed type EventPackageClaim struct { - ChainId uint32 `protobuf:"varint,1,opt,name=chain_id,json=chainId,proto3" json:"chain_id,omitempty"` - ChannelId uint32 `protobuf:"varint,2,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` - PackageType uint32 `protobuf:"varint,3,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` - ReceiveSequence uint64 `protobuf:"varint,4,opt,name=receive_sequence,json=receiveSequence,proto3" json:"receive_sequence,omitempty"` - SendSequence int64 `protobuf:"varint,5,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` - Crash bool `protobuf:"varint,6,opt,name=crash,proto3" json:"crash,omitempty"` - ErrorMsg string `protobuf:"bytes,7,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` - RelayFee string `protobuf:"bytes,8,opt,name=relay_fee,json=relayFee,proto3" json:"relay_fee,omitempty"` + SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` + DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` + ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + PackageType uint32 `protobuf:"varint,4,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` + ReceiveSequence uint64 `protobuf:"varint,5,opt,name=receive_sequence,json=receiveSequence,proto3" json:"receive_sequence,omitempty"` + SendSequence int64 `protobuf:"varint,6,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` + Crash bool `protobuf:"varint,7,opt,name=crash,proto3" json:"crash,omitempty"` + ErrorMsg string `protobuf:"bytes,8,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` + RelayFee string `protobuf:"bytes,9,opt,name=relay_fee,json=relayFee,proto3" json:"relay_fee,omitempty"` } func (m *EventPackageClaim) Reset() { *m = EventPackageClaim{} } @@ -67,9 +68,16 @@ func (m *EventPackageClaim) XXX_DiscardUnknown() { var xxx_messageInfo_EventPackageClaim proto.InternalMessageInfo -func (m *EventPackageClaim) GetChainId() uint32 { +func (m *EventPackageClaim) GetSrcChainId() uint32 { if m != nil { - return m.ChainId + return m.SrcChainId + } + return 0 +} + +func (m *EventPackageClaim) GetDestChainId() uint32 { + if m != nil { + return m.DestChainId } return 0 } @@ -130,28 +138,29 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/event.proto", fileDescriptor_3e254cedc4112fb0) } var fileDescriptor_3e254cedc4112fb0 = []byte{ - // 326 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xcd, 0x4e, 0xe3, 0x30, - 0x14, 0x85, 0xeb, 0xfe, 0xa6, 0x9e, 0x56, 0xd3, 0xb1, 0x66, 0x91, 0xce, 0x40, 0x14, 0x60, 0x13, - 0x84, 0x48, 0x54, 0xf1, 0x06, 0xa0, 0x22, 0x75, 0x81, 0x84, 0x02, 0x2b, 0x36, 0x91, 0xeb, 0x5c, - 0x92, 0xa8, 0x49, 0x1c, 0xec, 0x34, 0xa2, 0x6f, 0xd1, 0xc7, 0x62, 0xd9, 0x25, 0x4b, 0xd4, 0xbe, - 0x08, 0x8a, 0x63, 0x60, 0x65, 0x9d, 0xef, 0x3b, 0xb6, 0xe4, 0x7b, 0xf1, 0x11, 0xe3, 0x32, 0xe3, - 0xd2, 0xe3, 0x82, 0xb2, 0x14, 0xbc, 0x6a, 0xe6, 0x41, 0x05, 0x79, 0xe9, 0x16, 0x82, 0x97, 0x9c, - 0x4c, 0x1a, 0xeb, 0x36, 0xd6, 0xad, 0x66, 0xff, 0xa6, 0x0d, 0x09, 0x94, 0xf7, 0xb4, 0x56, 0xe1, - 0x74, 0xdb, 0xc6, 0x7f, 0xe6, 0xf5, 0xe5, 0x7b, 0xca, 0x56, 0x34, 0x82, 0x9b, 0x94, 0x26, 0x19, - 0x99, 0x62, 0x83, 0xc5, 0x34, 0xc9, 0x83, 0x24, 0x34, 0x91, 0x8d, 0x9c, 0xb1, 0x3f, 0x50, 0x79, - 0x11, 0x92, 0x63, 0x8c, 0x59, 0x4c, 0xf3, 0x1c, 0xd2, 0x5a, 0xb6, 0x95, 0x1c, 0x6a, 0xb2, 0x08, - 0xc9, 0x09, 0x1e, 0x15, 0xcd, 0x4b, 0x41, 0xb9, 0x29, 0xc0, 0xec, 0xa8, 0xc2, 0x2f, 0xcd, 0x1e, - 0x37, 0x05, 0x90, 0x73, 0x3c, 0x11, 0xc0, 0x20, 0xa9, 0x20, 0x90, 0xf0, 0xb2, 0x86, 0x9c, 0x81, - 0xd9, 0xb5, 0x91, 0xd3, 0xf5, 0x7f, 0x6b, 0xfe, 0xa0, 0x31, 0x39, 0xc3, 0x63, 0x09, 0x79, 0xf8, - 0xd3, 0xeb, 0xd9, 0xc8, 0xe9, 0xf8, 0xa3, 0x1a, 0x7e, 0x97, 0xfe, 0xe2, 0x1e, 0x13, 0x54, 0xc6, - 0x66, 0xdf, 0x46, 0x8e, 0xe1, 0x37, 0x81, 0xfc, 0xc7, 0x43, 0x10, 0x82, 0x8b, 0x20, 0x93, 0x91, - 0x39, 0xb0, 0x91, 0x33, 0xf4, 0x0d, 0x05, 0xee, 0x64, 0x54, 0x4b, 0x01, 0x29, 0xdd, 0x04, 0xcf, - 0x00, 0xa6, 0xd1, 0x48, 0x05, 0x6e, 0x01, 0xae, 0xe7, 0x6f, 0x7b, 0x0b, 0xed, 0xf6, 0x16, 0xfa, - 0xd8, 0x5b, 0x68, 0x7b, 0xb0, 0x5a, 0xbb, 0x83, 0xd5, 0x7a, 0x3f, 0x58, 0xad, 0xa7, 0x8b, 0x28, - 0x29, 0xe3, 0xf5, 0xd2, 0x65, 0x3c, 0xd3, 0x53, 0xd4, 0xc7, 0xa5, 0x0c, 0x57, 0xde, 0xeb, 0xd7, - 0x3e, 0xea, 0x8f, 0xcb, 0x65, 0x5f, 0x0d, 0xf8, 0xea, 0x33, 0x00, 0x00, 0xff, 0xff, 0xb7, 0xa8, - 0xb1, 0xcb, 0xad, 0x01, 0x00, 0x00, + // 338 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xcf, 0x4a, 0xeb, 0x40, + 0x14, 0xc6, 0x3b, 0xfd, 0x77, 0x9b, 0xb9, 0x2d, 0xb7, 0x77, 0xb8, 0x8b, 0xc0, 0xd5, 0x10, 0xeb, + 0x26, 0x22, 0x26, 0x14, 0xdf, 0xc0, 0x52, 0xa1, 0x0b, 0x41, 0xa2, 0x2b, 0x37, 0x61, 0x3a, 0x39, + 0x26, 0xa1, 0x49, 0x26, 0xce, 0xa4, 0xc1, 0xbe, 0x85, 0xef, 0xe3, 0x0b, 0xb8, 0xec, 0xd2, 0xa5, + 0xb4, 0x2f, 0x22, 0x93, 0x49, 0xed, 0x6a, 0x98, 0xdf, 0xf7, 0xe3, 0x1c, 0x0e, 0x1f, 0x3e, 0x61, + 0x5c, 0x66, 0x5c, 0x7a, 0x5c, 0x50, 0x96, 0x82, 0x57, 0x4d, 0x3d, 0xa8, 0x20, 0x2f, 0xdd, 0x42, + 0xf0, 0x92, 0x93, 0xb1, 0x4e, 0x5d, 0x9d, 0xba, 0xd5, 0x74, 0xf2, 0xde, 0xc6, 0x7f, 0xe7, 0xca, + 0xb8, 0xa7, 0x6c, 0x45, 0x23, 0x98, 0xa5, 0x34, 0xc9, 0x88, 0x8d, 0x87, 0x52, 0xb0, 0x80, 0xc5, + 0x34, 0xc9, 0x83, 0x24, 0x34, 0x91, 0x8d, 0x9c, 0x91, 0x8f, 0xa5, 0x60, 0x33, 0x85, 0x16, 0x21, + 0x99, 0xe0, 0x51, 0x08, 0xb2, 0x3c, 0x2a, 0xed, 0x5a, 0xf9, 0xad, 0xe0, 0xc1, 0x39, 0xc5, 0x98, + 0xc5, 0x34, 0xcf, 0x21, 0x55, 0x42, 0xa7, 0x16, 0x8c, 0x86, 0x2c, 0x42, 0x72, 0x86, 0x87, 0x85, + 0x5e, 0x1a, 0x94, 0x9b, 0x02, 0xcc, 0xae, 0x9e, 0xd0, 0xb0, 0xc7, 0x4d, 0x01, 0xe4, 0x02, 0x8f, + 0x05, 0x30, 0x48, 0x2a, 0x08, 0x24, 0xbc, 0xac, 0x21, 0x67, 0x60, 0xf6, 0x6c, 0xe4, 0x74, 0xfd, + 0x3f, 0x0d, 0x7f, 0x68, 0x30, 0x39, 0xc7, 0x23, 0x09, 0x79, 0x78, 0xf4, 0xfa, 0x36, 0x72, 0x3a, + 0xfe, 0x50, 0xc1, 0x1f, 0xe9, 0x1f, 0xee, 0x31, 0x41, 0x65, 0x6c, 0xfe, 0xb2, 0x91, 0x33, 0xf0, + 0xf5, 0x87, 0xfc, 0xc7, 0x06, 0x08, 0xc1, 0x45, 0x90, 0xc9, 0xc8, 0x1c, 0xd8, 0xc8, 0x31, 0xfc, + 0x41, 0x0d, 0xee, 0x64, 0xa4, 0x42, 0x01, 0x29, 0xdd, 0x04, 0xcf, 0x00, 0xa6, 0xa1, 0xc3, 0x1a, + 0xdc, 0x02, 0xdc, 0xcc, 0x3f, 0x76, 0x16, 0xda, 0xee, 0x2c, 0xf4, 0xb5, 0xb3, 0xd0, 0xdb, 0xde, + 0x6a, 0x6d, 0xf7, 0x56, 0xeb, 0x73, 0x6f, 0xb5, 0x9e, 0x2e, 0xa3, 0xa4, 0x8c, 0xd7, 0x4b, 0x97, + 0xf1, 0xcc, 0x6b, 0x2a, 0xd1, 0xcf, 0x95, 0x0c, 0x57, 0xde, 0xeb, 0xa1, 0x1f, 0x75, 0xb8, 0x5c, + 0xf6, 0xeb, 0x76, 0xae, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x44, 0xa0, 0x08, 0xcc, 0xbd, 0x01, + 0x00, 0x00, } func (m *EventPackageClaim) Marshal() (dAtA []byte, err error) { @@ -179,14 +188,14 @@ func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { copy(dAtA[i:], m.RelayFee) i = encodeVarintEvent(dAtA, i, uint64(len(m.RelayFee))) i-- - dAtA[i] = 0x42 + dAtA[i] = 0x4a } if len(m.ErrorMsg) > 0 { i -= len(m.ErrorMsg) copy(dAtA[i:], m.ErrorMsg) i = encodeVarintEvent(dAtA, i, uint64(len(m.ErrorMsg))) i-- - dAtA[i] = 0x3a + dAtA[i] = 0x42 } if m.Crash { i-- @@ -196,30 +205,35 @@ func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { dAtA[i] = 0 } i-- - dAtA[i] = 0x30 + dAtA[i] = 0x38 } if m.SendSequence != 0 { i = encodeVarintEvent(dAtA, i, uint64(m.SendSequence)) i-- - dAtA[i] = 0x28 + dAtA[i] = 0x30 } if m.ReceiveSequence != 0 { i = encodeVarintEvent(dAtA, i, uint64(m.ReceiveSequence)) i-- - dAtA[i] = 0x20 + dAtA[i] = 0x28 } if m.PackageType != 0 { i = encodeVarintEvent(dAtA, i, uint64(m.PackageType)) i-- - dAtA[i] = 0x18 + dAtA[i] = 0x20 } if m.ChannelId != 0 { i = encodeVarintEvent(dAtA, i, uint64(m.ChannelId)) i-- + dAtA[i] = 0x18 + } + if m.DestChainId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.DestChainId)) + i-- dAtA[i] = 0x10 } - if m.ChainId != 0 { - i = encodeVarintEvent(dAtA, i, uint64(m.ChainId)) + if m.SrcChainId != 0 { + i = encodeVarintEvent(dAtA, i, uint64(m.SrcChainId)) i-- dAtA[i] = 0x8 } @@ -243,8 +257,11 @@ func (m *EventPackageClaim) Size() (n int) { } var l int _ = l - if m.ChainId != 0 { - n += 1 + sovEvent(uint64(m.ChainId)) + if m.SrcChainId != 0 { + n += 1 + sovEvent(uint64(m.SrcChainId)) + } + if m.DestChainId != 0 { + n += 1 + sovEvent(uint64(m.DestChainId)) } if m.ChannelId != 0 { n += 1 + sovEvent(uint64(m.ChannelId)) @@ -309,9 +326,9 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { switch fieldNum { case 1: if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field ChainId", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SrcChainId", wireType) } - m.ChainId = 0 + m.SrcChainId = 0 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowEvent @@ -321,12 +338,31 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - m.ChainId |= uint32(b&0x7F) << shift + m.SrcChainId |= uint32(b&0x7F) << shift if b < 0x80 { break } } case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field DestChainId", wireType) + } + m.DestChainId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.DestChainId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) } @@ -345,7 +381,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { break } } - case 3: + case 4: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field PackageType", wireType) } @@ -364,7 +400,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { break } } - case 4: + case 5: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field ReceiveSequence", wireType) } @@ -383,7 +419,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { break } } - case 5: + case 6: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field SendSequence", wireType) } @@ -402,7 +438,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { break } } - case 6: + case 7: if wireType != 0 { return fmt.Errorf("proto: wrong wireType = %d for field Crash", wireType) } @@ -422,7 +458,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { } } m.Crash = bool(v != 0) - case 7: + case 8: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field ErrorMsg", wireType) } @@ -454,7 +490,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { } m.ErrorMsg = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex - case 8: + case 9: if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field RelayFee", wireType) } diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 927060786f..fad8898b65 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -17,8 +17,8 @@ type CrossChainKeeper interface { GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication GetSrcChainID() sdk.ChainID IsDestChainSupported(chainID sdk.ChainID) bool - GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 - IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) + GetReceiveSequence(ctx sdk.Context, srcChainID sdk.ChainID, channelID sdk.ChannelID) uint64 + IncrReceiveSequence(ctx sdk.Context, srcChainID sdk.ChainID, channelID sdk.ChannelID) } type BankKeeper interface { diff --git a/x/oracle/types/msgs.go b/x/oracle/types/msgs.go index adb779a2ca..4aff4851b6 100644 --- a/x/oracle/types/msgs.go +++ b/x/oracle/types/msgs.go @@ -15,8 +15,10 @@ const ( BLSSignatureLength = 96 ) -type BLSPublicKey [BLSPublicKeyLength]byte -type BLSSignature [BLSSignatureLength]byte +type ( + BLSPublicKey [BLSPublicKeyLength]byte + BLSSignature [BLSSignatureLength]byte +) func NewMsgClaim(fromAddr string, srcShainId, destChainId uint32, sequence uint64, timestamp uint64, payload []byte, voteAddrSet []uint64, aggSignature []byte) *MsgClaim { return &MsgClaim{ @@ -59,7 +61,7 @@ func (m *MsgClaim) ValidateBasic() error { } if len(m.Payload) == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, fmt.Sprintf("payload should not be empty")) + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "payload should not be empty") } if len(m.VoteAddressSet) != ValidatorBitSetLength { @@ -74,9 +76,7 @@ func (m *MsgClaim) ValidateBasic() error { } if m.Timestamp == 0 { - return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, - fmt.Sprintf("timestamp should not be 0"), - ) + return sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "timestamp should not be 0") } return nil diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go index d584f7d0fb..7b48f9cb78 100644 --- a/x/oracle/types/oracle.pb.go +++ b/x/oracle/types/oracle.pb.go @@ -5,8 +5,6 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/cosmos-proto" - _ "github.com/gogo/protobuf/gogoproto" proto "github.com/gogo/protobuf/proto" io "io" math "math" @@ -84,21 +82,19 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/oracle.proto", fileDescriptor_3dec273964b5043c) } var fileDescriptor_3dec273964b5043c = []byte{ - // 212 bytes of a gzipped FileDescriptorProto + // 190 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, - 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0x29, 0x91, 0xf4, - 0xfc, 0xf4, 0x7c, 0xb0, 0xa4, 0x3e, 0x88, 0x05, 0x51, 0x27, 0x25, 0x09, 0x51, 0x17, 0x0f, 0x91, - 0x80, 0x6a, 0x02, 0x73, 0x94, 0x92, 0xb9, 0xd8, 0x02, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0x85, 0xd4, - 0xb9, 0xf8, 0x8b, 0x52, 0x73, 0x12, 0x2b, 0x53, 0x8b, 0xe2, 0x4b, 0x32, 0x73, 0x53, 0xf3, 0x4b, - 0x4b, 0x24, 0x18, 0x15, 0x18, 0x35, 0x58, 0x82, 0xf8, 0xa0, 0xc2, 0x21, 0x10, 0x51, 0x21, 0x03, - 0x2e, 0x11, 0x98, 0xc2, 0xa4, 0xc4, 0xe4, 0xec, 0xfc, 0xb4, 0x34, 0xb0, 0x06, 0x09, 0x26, 0xb0, - 0x6a, 0x21, 0xa8, 0x9c, 0x13, 0x44, 0x0a, 0xa4, 0xc9, 0xc9, 0xf5, 0xc4, 0x23, 0x39, 0xc6, 0x0b, - 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, - 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xb4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, - 0xa1, 0xee, 0x82, 0x52, 0xba, 0xc5, 0x29, 0xd9, 0xfa, 0x15, 0x30, 0x8f, 0x97, 0x54, 0x16, 0xa4, - 0x16, 0x27, 0xb1, 0x81, 0x9d, 0x6c, 0x0c, 0x08, 0x00, 0x00, 0xff, 0xff, 0xe1, 0x78, 0xe6, 0x29, - 0x16, 0x01, 0x00, 0x00, + 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0xa5, 0x64, 0x2e, + 0xb6, 0x80, 0xc4, 0xa2, 0xc4, 0xdc, 0x62, 0x21, 0x75, 0x2e, 0xfe, 0xa2, 0xd4, 0x9c, 0xc4, 0xca, + 0xd4, 0xa2, 0xf8, 0x92, 0xcc, 0xdc, 0xd4, 0xfc, 0xd2, 0x12, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x96, + 0x20, 0x3e, 0xa8, 0x70, 0x08, 0x44, 0x54, 0xc8, 0x80, 0x4b, 0x04, 0xa6, 0x30, 0x29, 0x31, 0x39, + 0x3b, 0x3f, 0x2d, 0x0d, 0xac, 0x41, 0x82, 0x09, 0xac, 0x5a, 0x08, 0x2a, 0xe7, 0x04, 0x91, 0x02, + 0x69, 0x72, 0x72, 0x3d, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, + 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xed, 0xf4, + 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, 0xd3, 0x21, 0x94, 0x6e, 0x71, + 0x4a, 0xb6, 0x7e, 0x05, 0xcc, 0x1f, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0x4f, 0x18, + 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x77, 0x36, 0xc0, 0xd0, 0xe5, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index 82b8058075..14161570d5 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -6,10 +6,8 @@ package types import ( context "context" fmt "fmt" - _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" - _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" math "math" ) @@ -28,18 +26,16 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package func init() { proto.RegisterFile("cosmos/oracle/v1/query.proto", fileDescriptor_9f804c4644f3aaef) } var fileDescriptor_9f804c4644f3aaef = []byte{ - // 172 bytes of a gzipped FileDescriptorProto + // 133 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x80, 0xc8, 0xea, 0x41, 0x64, 0xf5, - 0xca, 0x0c, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x92, 0xfa, 0x20, 0x16, 0x44, 0x9d, 0x94, - 0x4c, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x7e, 0x62, 0x41, 0xa6, 0x7e, 0x62, 0x5e, 0x5e, 0x7e, - 0x49, 0x62, 0x49, 0x66, 0x7e, 0x5e, 0x31, 0x44, 0xd6, 0x88, 0x9d, 0x8b, 0x35, 0x10, 0x64, 0xa8, - 0x93, 0xeb, 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, 0xa7, 0x67, 0x96, - 0x64, 0x94, 0x26, 0xe9, 0x25, 0xe7, 0xe7, 0xea, 0x43, 0x5d, 0x04, 0xa1, 0x74, 0x8b, 0x53, 0xb2, - 0xf5, 0x2b, 0x60, 0xce, 0x2b, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x1b, 0x6b, 0x0c, 0x08, - 0x00, 0x00, 0xff, 0xff, 0xb5, 0xe1, 0x17, 0x67, 0xbc, 0x00, 0x00, 0x00, + 0xca, 0x0c, 0x8d, 0xd8, 0xb9, 0x58, 0x03, 0x41, 0x0a, 0x9c, 0x5c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, + 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, + 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, + 0x57, 0x1f, 0x6a, 0x3a, 0x84, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, 0x80, 0x59, 0x55, 0x52, 0x59, + 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0xb6, 0xc8, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xc4, 0x7d, + 0x86, 0x88, 0x00, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. From 0040ccee6187799fe93043114bc9c9d9b63ff8e2 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 14:15:50 +0800 Subject: [PATCH 33/50] fix lint error --- proto/cosmos/oracle/v1/tx.proto | 1 + x/oracle/keeper/keeper.go | 8 ++++---- x/oracle/types/errors.go | 2 +- x/oracle/types/tx.pb.go | 2 ++ 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/proto/cosmos/oracle/v1/tx.proto b/proto/cosmos/oracle/v1/tx.proto index 34a4ac008f..e0b2920a76 100644 --- a/proto/cosmos/oracle/v1/tx.proto +++ b/proto/cosmos/oracle/v1/tx.proto @@ -10,6 +10,7 @@ import "cosmos/msg/v1/msg.proto"; // Msg defines the oracle Msg service. service Msg { + // Claim defines a method for claiming oracle messages rpc Claim(MsgClaim) returns (MsgClaimResponse); } diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index cce1c7605e..85ed45e86c 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -117,7 +117,7 @@ func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Valid func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { historicalInfo, ok := k.StakingKeeper.GetHistoricalInfo(ctx, ctx.BlockHeight()) if !ok { - return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("get historical validators failed")) + return sdkerrors.Wrapf(types.ErrValidatorSet, "get historical validators failed") } validators := historicalInfo.Valset @@ -126,12 +126,12 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { return err } if !inturn { - return sdkerrors.Wrapf(types.ErrValidatorNotInTurn, fmt.Sprintf("validator is not in turn")) + return sdkerrors.Wrapf(types.ErrRelayerNotInTurn, fmt.Sprintf("relayer(%s) is not in turn", claim.FromAddress)) } validatorsBitSet := bitset.From(claim.VoteAddressSet) if validatorsBitSet.Count() > uint(len(validators)) { - return sdkerrors.Wrapf(types.ErrValidatorSet, fmt.Sprintf("number of validator set is larger than validators")) + return sdkerrors.Wrapf(types.ErrValidatorSet, "number of validator set is larger than validators") } votedPubKeys := make([]bls.PublicKey, 0, validatorsBitSet.Count()) @@ -159,7 +159,7 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { } if !aggSig.FastAggregateVerify(votedPubKeys, claim.GetBlsSignBytes()) { - return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("signature verify failed")) + return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, "signature verify failed") } return nil diff --git a/x/oracle/types/errors.go b/x/oracle/types/errors.go index 30ac76fe9f..5576d1003a 100644 --- a/x/oracle/types/errors.go +++ b/x/oracle/types/errors.go @@ -14,7 +14,7 @@ var ( ErrBlsVotesNotEnough = sdkerrors.Register(ModuleName, 10, "bls votes is not enough") ErrInvalidBlsSignature = sdkerrors.Register(ModuleName, 11, "bls signature is invalid") ErrNotRelayer = sdkerrors.Register(ModuleName, 12, "sender is not a relayer") - ErrValidatorNotInTurn = sdkerrors.Register(ModuleName, 13, "validator is not in turn") + ErrRelayerNotInTurn = sdkerrors.Register(ModuleName, 13, "relayer is not in turn") ErrInvalidDestChainId = sdkerrors.Register(ModuleName, 14, "dest chain id is invalid") ErrInvalidSrcChainId = sdkerrors.Register(ModuleName, 15, "src chain id is invalid") ErrInvalidAddress = sdkerrors.Register(ModuleName, 16, "address is invalid") diff --git a/x/oracle/types/tx.pb.go b/x/oracle/types/tx.pb.go index 2db62ec887..72a3c3e2dc 100644 --- a/x/oracle/types/tx.pb.go +++ b/x/oracle/types/tx.pb.go @@ -185,6 +185,7 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type MsgClient interface { + // Claim defines a method for claiming oracle messages Claim(ctx context.Context, in *MsgClaim, opts ...grpc.CallOption) (*MsgClaimResponse, error) } @@ -207,6 +208,7 @@ func (c *msgClient) Claim(ctx context.Context, in *MsgClaim, opts ...grpc.CallOp // MsgServer is the server API for Msg service. type MsgServer interface { + // Claim defines a method for claiming oracle messages Claim(context.Context, *MsgClaim) (*MsgClaimResponse, error) } From 29dd2bfc15adeaf5da812e591d90fe34abbf8b32 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 17:00:34 +0800 Subject: [PATCH 34/50] add ack relayer fee to cross chain package header --- go.mod | 2 +- proto/cosmos/oracle/v1/event.proto | 3 +- simapp/test_helpers.go | 1 + types/cross_chain.go | 102 +++++++++++++++---------- x/crosschain/keeper/keeper.go | 20 ++--- x/crosschain/keeper/keeper_test.go | 16 +--- x/oracle/keeper/msg_server.go | 37 ++++----- x/oracle/keeper/msg_server_test.go | 17 ++++- x/oracle/types/event.pb.go | 118 +++++++++++++++++++++-------- x/oracle/types/expected_keepers.go | 7 +- 10 files changed, 203 insertions(+), 120 deletions(-) diff --git a/go.mod b/go.mod index c551371198..56d8c55892 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,6 @@ require ( github.com/cosmos/ledger-cosmos-go v0.11.1 github.com/ethereum/go-ethereum v1.10.19 github.com/evmos/ethermint v0.6.1-0.20220919141022-34226aa7b1fa - github.com/go-kit/kit v0.12.0 github.com/gogo/gateway v1.1.0 github.com/gogo/protobuf v1.3.3 github.com/golang/mock v1.6.0 @@ -96,6 +95,7 @@ require ( github.com/felixge/httpsnoop v1.0.1 // indirect github.com/ferranbt/fastssz v0.0.0-20210905181407-59cf6761a7d5 // indirect github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/go-kit/kit v0.12.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect diff --git a/proto/cosmos/oracle/v1/event.proto b/proto/cosmos/oracle/v1/event.proto index 733ee975dc..1f99602d2e 100644 --- a/proto/cosmos/oracle/v1/event.proto +++ b/proto/cosmos/oracle/v1/event.proto @@ -15,5 +15,6 @@ message EventPackageClaim { int64 send_sequence = 6; bool crash = 7; string error_msg = 8; - string relay_fee = 9; + string syn_relay_fee = 9; + string ack_relay_fee = 10; } \ No newline at end of file diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index 9b7a5acbf5..48956bd9a3 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -165,6 +165,7 @@ func genesisStateWithValSet(t *testing.T, require.NoError(t, err) validator := stakingtypes.Validator{ OperatorAddress: sdk.AccAddress(val.Address).String(), + RelayerAddress: sdk.AccAddress(val.Address).String(), ConsensusPubkey: pkAny, Jailed: false, Status: stakingtypes.Bonded, diff --git a/types/cross_chain.go b/types/cross_chain.go index b12b48e852..adeed33cf0 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -3,9 +3,7 @@ package types import ( "encoding/binary" "fmt" - "math" "math/big" - "strconv" ) type CrossChainPackageType uint8 @@ -32,28 +30,6 @@ func IsValidCrossChainPackageType(packageType CrossChainPackageType) bool { return packageType == SynCrossChainPackageType || packageType == AckCrossChainPackageType || packageType == FailAckCrossChainPackageType } -func ParseChannelID(input string) (ChannelID, error) { - channelID, err := strconv.Atoi(input) - if err != nil { - return ChannelID(0), err - } - if channelID > math.MaxInt8 || channelID < 0 { - return ChannelID(0), fmt.Errorf("channelID must be in [0, 255]") - } - return ChannelID(channelID), nil -} - -func ParseChainID(input string) (ChainID, error) { - chainID, err := strconv.Atoi(input) - if err != nil { - return ChainID(0), err - } - if chainID > math.MaxUint16 || chainID < 0 { - return ChainID(0), fmt.Errorf("cross chainID must be in [0, 65535]") - } - return ChainID(chainID), nil -} - type CrossChainApplication interface { ExecuteSynPackage(ctx Context, payload []byte, relayerFee *big.Int) ExecuteResult ExecuteAckPackage(ctx Context, payload []byte) ExecuteResult @@ -81,31 +57,79 @@ const ( CrossChainFeeLength = 32 PackageTypeLength = 1 TimestampLength = 8 - PackageHeaderLength = CrossChainFeeLength + TimestampLength + PackageTypeLength + + SynPackageHeaderLength = 2*CrossChainFeeLength + TimestampLength + PackageTypeLength + AckPackageHeaderLength = CrossChainFeeLength + TimestampLength + PackageTypeLength +) + +func GetPackageHeaderLength(packageType CrossChainPackageType) int { + if packageType == SynCrossChainPackageType { + return SynPackageHeaderLength + } + return AckPackageHeaderLength +} + +type PackageHeader struct { + PackageType CrossChainPackageType + Timestamp uint64 + SynRelayerFee *big.Int + AckRelayerFee *big.Int +} + +var ( + NilAckRelayerFee = big.NewInt(0) // For ack packages, the ack relayer fee should be nil, and it would not be encoded into package header ) -func EncodePackageHeader(packageType CrossChainPackageType, timestamp uint64, relayerFee big.Int) []byte { - packageHeader := make([]byte, PackageHeaderLength) - packageHeader[0] = uint8(packageType) +func EncodePackageHeader(header PackageHeader) []byte { + packageHeader := make([]byte, GetPackageHeaderLength(header.PackageType)) + packageHeader[0] = uint8(header.PackageType) timestampBytes := make([]byte, TimestampLength) - binary.BigEndian.PutUint64(timestampBytes, timestamp) + binary.BigEndian.PutUint64(timestampBytes, header.Timestamp) copy(packageHeader[PackageTypeLength:PackageTypeLength+TimestampLength], timestampBytes) - length := len(relayerFee.Bytes()) - copy(packageHeader[PackageHeaderLength-length:PackageHeaderLength], relayerFee.Bytes()) + synRelayerFeeLength := len(header.SynRelayerFee.Bytes()) + copy(packageHeader[AckPackageHeaderLength-synRelayerFeeLength:AckPackageHeaderLength], header.SynRelayerFee.Bytes()) + + // add ack relayer fee to header for syn package + if header.PackageType == SynCrossChainPackageType { + ackRelayerFeeLength := len(header.AckRelayerFee.Bytes()) + copy(packageHeader[SynPackageHeaderLength-ackRelayerFeeLength:SynPackageHeaderLength], header.AckRelayerFee.Bytes()) + } + return packageHeader } -func DecodePackageHeader(packageHeader []byte) (packageType CrossChainPackageType, timestamp uint64, relayFee big.Int, err error) { - if len(packageHeader) < PackageHeaderLength { - err = fmt.Errorf("length of packageHeader is less than %d", PackageHeaderLength) - return +func DecodePackageHeader(packageHeader []byte) (PackageHeader, error) { + if len(packageHeader) == 0 { + return PackageHeader{}, fmt.Errorf("empty package header") + } + + packageType := CrossChainPackageType(packageHeader[0]) + if !IsValidCrossChainPackageType(packageType) { + return PackageHeader{}, fmt.Errorf("package type %d is invalid", packageType) } - packageType = CrossChainPackageType(packageHeader[0]) - timestamp = binary.BigEndian.Uint64(packageHeader[PackageTypeLength : PackageTypeLength+TimestampLength]) + headerLength := GetPackageHeaderLength(packageType) + if len(packageHeader) < headerLength { + err := fmt.Errorf("length of packageHeader is less than %d", headerLength) + return PackageHeader{}, err + } + + timestamp := binary.BigEndian.Uint64(packageHeader[PackageTypeLength : PackageTypeLength+TimestampLength]) + + synRelayFee := big.NewInt(0).SetBytes(packageHeader[PackageTypeLength+TimestampLength : AckPackageHeaderLength]) + + header := PackageHeader{ + PackageType: packageType, + Timestamp: timestamp, + SynRelayerFee: synRelayFee, + AckRelayerFee: big.NewInt(0), + } + + if packageType == SynCrossChainPackageType { + header.AckRelayerFee = big.NewInt(0).SetBytes(packageHeader[AckPackageHeaderLength:SynPackageHeaderLength]) + } - relayFee.SetBytes(packageHeader[PackageTypeLength+TimestampLength : PackageHeaderLength]) - return + return header, nil } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index c7064b9510..50784a6170 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -67,18 +67,9 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) } -// CreateRawIBCPackage creates a cross chain package with default cross chain fee -func (k Keeper) CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte, -) (uint64, error) { - relayerFee := k.GetRelayerFeeParam(ctx) - - return k.CreateRawIBCPackageWithFee(ctx, destChainID, channelID, packageType, packageLoad, *relayerFee) -} - // CreateRawIBCPackageWithFee creates a cross chain package with given cross chain fee func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee big.Int, + packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, ) (uint64, error) { if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, destChainID, channelID) != sdk.ChannelAllow { return 0, fmt.Errorf("channel %d is not allowed to write syn package", channelID) @@ -92,7 +83,12 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai } // Assemble the package header - packageHeader := sdk.EncodePackageHeader(packageType, uint64(ctx.BlockTime().Unix()), relayerFee) + packageHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ + PackageType: packageType, + Timestamp: uint64(ctx.BlockTime().Unix()), + SynRelayerFee: synRelayerFee, + AckRelayerFee: ackRelayerFee, + }) kvStore.Set(key, append(packageHeader, packageLoad...)) @@ -106,7 +102,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai PackageType: uint32(packageType), Timestamp: uint64(ctx.BlockTime().Unix()), PackageLoad: packageLoad, - RelayerFee: relayerFee.String(), + RelayerFee: synRelayerFee.String(), }) if err != nil { return 0, err diff --git a/x/crosschain/keeper/keeper_test.go b/x/crosschain/keeper/keeper_test.go index 036a08869b..9940a14e33 100644 --- a/x/crosschain/keeper/keeper_test.go +++ b/x/crosschain/keeper/keeper_test.go @@ -3,13 +3,14 @@ package keeper_test import ( "testing" + "github.com/stretchr/testify/suite" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtime "github.com/tendermint/tendermint/types/time" + "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/crosschain/testutil" "github.com/cosmos/cosmos-sdk/x/crosschain/types" - "github.com/stretchr/testify/suite" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmtime "github.com/tendermint/tendermint/types/time" ) type TestSuite struct { @@ -90,15 +91,6 @@ func (s *TestSuite) TestRegisterChannel() { s.Require().ErrorContains(err, "nil cross chain app") } -func (s *TestSuite) TestCreateIBCPackage() { - sequence, err := s.app.CrossChainKeeper.CreateRawIBCPackage(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sdk.CrossChainPackageType(1), []byte("test payload")) - s.Require().NoError(err) - s.Require().EqualValues(0, sequence) - - _, err = s.app.CrossChainKeeper.GetIBCPackage(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sequence) - s.Require().NoError(err) -} - func (s *TestSuite) TestSetChannelSendPermission() { s.app.CrossChainKeeper.SetChannelSendPermission(s.ctx, sdk.ChainID(1), sdk.ChannelID(1), sdk.ChannelAllow) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index b5caeb88de..b3f996e334 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -96,41 +96,41 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) } - packageType, timestamp, relayFee, err := sdk.DecodePackageHeader(pack.Payload) + packageHeader, err := sdk.DecodePackageHeader(pack.Payload) if err != nil { return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "payload header is invalid") } - if timestamp != req.Timestamp { - return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, timestamp) + if packageHeader.Timestamp != req.Timestamp { + return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, packageHeader.Timestamp) } - if !sdk.IsValidCrossChainPackageType(packageType) { - return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageType)) + if !sdk.IsValidCrossChainPackageType(packageHeader.PackageType) { + return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageHeader.PackageType)) } bondDenom := oracleKeeper.StakingKeeper.BondDenom(ctx) - fee := sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(&relayFee)}} + fee := sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(packageHeader.SynRelayerFee)}} err = oracleKeeper.SendCoinsToFeeCollector(ctx, fee) if err != nil { return nil, err } cacheCtx, write := ctx.CacheContext() - crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageType, &relayFee) + crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageHeader.PackageType, packageHeader.SynRelayerFee) if result.IsOk() { write() } // write ack package var sendSequence int64 = -1 - if packageType == sdk.SynCrossChainPackageType { + if packageHeader.PackageType == sdk.SynCrossChainPackageType { if crash { var ibcErr error var sendSeq uint64 - if len(pack.Payload) >= sdk.PackageHeaderLength { - sendSeq, ibcErr = oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, - pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.PackageHeaderLength:]) + if len(pack.Payload) >= sdk.SynPackageHeaderLength { + sendSeq, ibcErr = oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, chainId, + pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.SynPackageHeaderLength:], packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) } else { logger.Error("found payload without header", "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) return nil, sdkerrors.Wrapf(types.ErrInvalidPackage, "payload without header") @@ -142,8 +142,8 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch } sendSequence = int64(sendSeq) } else if len(result.Payload) != 0 { - sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackage(ctx, chainId, - pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload) + sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, chainId, + pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload, packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) if err != nil { logger.Error("failed to write AckCrossChainPackage", "err", err) return nil, err @@ -156,10 +156,11 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch SrcChainId: req.SrcChainId, DestChainId: req.DestChainId, ChannelId: uint32(pack.ChannelId), - PackageType: uint32(packageType), + PackageType: uint32(packageHeader.PackageType), ReceiveSequence: pack.Sequence, SendSequence: sendSequence, - RelayFee: relayFee.String(), + SynRelayFee: packageHeader.SynRelayerFee.String(), + AckRelayFee: packageHeader.AckRelayerFee.String(), Crash: crash, ErrorMsg: result.ErrMsg(), } @@ -182,11 +183,11 @@ func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte switch packageType { case sdk.SynCrossChainPackageType: - result = app.ExecuteSynPackage(ctx, payload[sdk.PackageHeaderLength:], relayerFee) + result = app.ExecuteSynPackage(ctx, payload[sdk.SynPackageHeaderLength:], relayerFee) case sdk.AckCrossChainPackageType: - result = app.ExecuteAckPackage(ctx, payload[sdk.PackageHeaderLength:]) + result = app.ExecuteAckPackage(ctx, payload[sdk.AckPackageHeaderLength:]) case sdk.FailAckCrossChainPackageType: - result = app.ExecuteFailAckPackage(ctx, payload[sdk.PackageHeaderLength:]) + result = app.ExecuteFailAckPackage(ctx, payload[sdk.AckPackageHeaderLength:]) default: panic(fmt.Sprintf("receive unexpected package type %d", packageType)) } diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index a3934b7292..34429cac07 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -50,7 +50,12 @@ func (s *TestSuite) TestClaim() { validatorMap[validator.RelayerAddress] = idx } - payloadHeader := sdk.EncodePackageHeader(sdk.SynCrossChainPackageType, 1992, *big.NewInt(1)) + payloadHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ + PackageType: sdk.SynCrossChainPackageType, + Timestamp: 1992, + SynRelayerFee: big.NewInt(1), + AckRelayerFee: big.NewInt(1), + }) testPackage := types.Package{ ChannelId: 1, @@ -110,6 +115,9 @@ func (s *TestSuite) TestInvalidClaim() { validatorMap[validator.RelayerAddress] = idx } + println("------------------") + println("relayer: ", validators[0].RelayerAddress) + msgClaim := types.MsgClaim{ FromAddress: validators[0].RelayerAddress, SrcChainId: 56, @@ -147,7 +155,12 @@ func (s *TestSuite) TestInvalidClaim() { s.Require().Contains(err.Error(), "decode payload error") // invalid timestamp - payloadHeader := sdk.EncodePackageHeader(sdk.SynCrossChainPackageType, 1993, *big.NewInt(1)) + payloadHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ + PackageType: sdk.SynCrossChainPackageType, + Timestamp: 1993, + SynRelayerFee: big.NewInt(1), + AckRelayerFee: big.NewInt(1), + }) testPackage := types.Package{ ChannelId: 1, Sequence: 0, diff --git a/x/oracle/types/event.pb.go b/x/oracle/types/event.pb.go index 0ac650ac15..4220a3695e 100644 --- a/x/oracle/types/event.pb.go +++ b/x/oracle/types/event.pb.go @@ -32,7 +32,8 @@ type EventPackageClaim struct { SendSequence int64 `protobuf:"varint,6,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` Crash bool `protobuf:"varint,7,opt,name=crash,proto3" json:"crash,omitempty"` ErrorMsg string `protobuf:"bytes,8,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` - RelayFee string `protobuf:"bytes,9,opt,name=relay_fee,json=relayFee,proto3" json:"relay_fee,omitempty"` + SynRelayFee string `protobuf:"bytes,9,opt,name=syn_relay_fee,json=synRelayFee,proto3" json:"syn_relay_fee,omitempty"` + AckRelayFee string `protobuf:"bytes,10,opt,name=ack_relay_fee,json=ackRelayFee,proto3" json:"ack_relay_fee,omitempty"` } func (m *EventPackageClaim) Reset() { *m = EventPackageClaim{} } @@ -124,9 +125,16 @@ func (m *EventPackageClaim) GetErrorMsg() string { return "" } -func (m *EventPackageClaim) GetRelayFee() string { +func (m *EventPackageClaim) GetSynRelayFee() string { if m != nil { - return m.RelayFee + return m.SynRelayFee + } + return "" +} + +func (m *EventPackageClaim) GetAckRelayFee() string { + if m != nil { + return m.AckRelayFee } return "" } @@ -138,29 +146,30 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/event.proto", fileDescriptor_3e254cedc4112fb0) } var fileDescriptor_3e254cedc4112fb0 = []byte{ - // 338 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x44, 0x91, 0xcf, 0x4a, 0xeb, 0x40, - 0x14, 0xc6, 0x3b, 0xfd, 0x77, 0x9b, 0xb9, 0x2d, 0xb7, 0x77, 0xb8, 0x8b, 0xc0, 0xd5, 0x10, 0xeb, - 0x26, 0x22, 0x26, 0x14, 0xdf, 0xc0, 0x52, 0xa1, 0x0b, 0x41, 0xa2, 0x2b, 0x37, 0x61, 0x3a, 0x39, - 0x26, 0xa1, 0x49, 0x26, 0xce, 0xa4, 0xc1, 0xbe, 0x85, 0xef, 0xe3, 0x0b, 0xb8, 0xec, 0xd2, 0xa5, - 0xb4, 0x2f, 0x22, 0x93, 0x49, 0xed, 0x6a, 0x98, 0xdf, 0xf7, 0xe3, 0x1c, 0x0e, 0x1f, 0x3e, 0x61, - 0x5c, 0x66, 0x5c, 0x7a, 0x5c, 0x50, 0x96, 0x82, 0x57, 0x4d, 0x3d, 0xa8, 0x20, 0x2f, 0xdd, 0x42, - 0xf0, 0x92, 0x93, 0xb1, 0x4e, 0x5d, 0x9d, 0xba, 0xd5, 0x74, 0xf2, 0xde, 0xc6, 0x7f, 0xe7, 0xca, - 0xb8, 0xa7, 0x6c, 0x45, 0x23, 0x98, 0xa5, 0x34, 0xc9, 0x88, 0x8d, 0x87, 0x52, 0xb0, 0x80, 0xc5, - 0x34, 0xc9, 0x83, 0x24, 0x34, 0x91, 0x8d, 0x9c, 0x91, 0x8f, 0xa5, 0x60, 0x33, 0x85, 0x16, 0x21, - 0x99, 0xe0, 0x51, 0x08, 0xb2, 0x3c, 0x2a, 0xed, 0x5a, 0xf9, 0xad, 0xe0, 0xc1, 0x39, 0xc5, 0x98, - 0xc5, 0x34, 0xcf, 0x21, 0x55, 0x42, 0xa7, 0x16, 0x8c, 0x86, 0x2c, 0x42, 0x72, 0x86, 0x87, 0x85, - 0x5e, 0x1a, 0x94, 0x9b, 0x02, 0xcc, 0xae, 0x9e, 0xd0, 0xb0, 0xc7, 0x4d, 0x01, 0xe4, 0x02, 0x8f, - 0x05, 0x30, 0x48, 0x2a, 0x08, 0x24, 0xbc, 0xac, 0x21, 0x67, 0x60, 0xf6, 0x6c, 0xe4, 0x74, 0xfd, - 0x3f, 0x0d, 0x7f, 0x68, 0x30, 0x39, 0xc7, 0x23, 0x09, 0x79, 0x78, 0xf4, 0xfa, 0x36, 0x72, 0x3a, - 0xfe, 0x50, 0xc1, 0x1f, 0xe9, 0x1f, 0xee, 0x31, 0x41, 0x65, 0x6c, 0xfe, 0xb2, 0x91, 0x33, 0xf0, - 0xf5, 0x87, 0xfc, 0xc7, 0x06, 0x08, 0xc1, 0x45, 0x90, 0xc9, 0xc8, 0x1c, 0xd8, 0xc8, 0x31, 0xfc, - 0x41, 0x0d, 0xee, 0x64, 0xa4, 0x42, 0x01, 0x29, 0xdd, 0x04, 0xcf, 0x00, 0xa6, 0xa1, 0xc3, 0x1a, - 0xdc, 0x02, 0xdc, 0xcc, 0x3f, 0x76, 0x16, 0xda, 0xee, 0x2c, 0xf4, 0xb5, 0xb3, 0xd0, 0xdb, 0xde, - 0x6a, 0x6d, 0xf7, 0x56, 0xeb, 0x73, 0x6f, 0xb5, 0x9e, 0x2e, 0xa3, 0xa4, 0x8c, 0xd7, 0x4b, 0x97, - 0xf1, 0xcc, 0x6b, 0x2a, 0xd1, 0xcf, 0x95, 0x0c, 0x57, 0xde, 0xeb, 0xa1, 0x1f, 0x75, 0xb8, 0x5c, - 0xf6, 0xeb, 0x76, 0xae, 0xbf, 0x03, 0x00, 0x00, 0xff, 0xff, 0x44, 0xa0, 0x08, 0xcc, 0xbd, 0x01, - 0x00, 0x00, + // 353 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0xd1, 0xcd, 0x4e, 0xab, 0x40, + 0x14, 0xc0, 0xf1, 0x4e, 0xbf, 0x6e, 0x99, 0xb6, 0xb9, 0x95, 0xb8, 0x20, 0x51, 0x09, 0xd6, 0x0d, + 0xc6, 0x08, 0x69, 0x7c, 0x03, 0x9b, 0x9a, 0x74, 0x61, 0x62, 0xd0, 0x95, 0x1b, 0x32, 0x1d, 0x8e, + 0x40, 0x80, 0x01, 0x67, 0x28, 0x91, 0xb7, 0xf0, 0xb1, 0x5c, 0x76, 0xe9, 0xd2, 0xb4, 0x89, 0xcf, + 0x61, 0x06, 0xa8, 0x75, 0x45, 0xf8, 0x9f, 0x5f, 0x20, 0x33, 0x07, 0x9f, 0xd2, 0x54, 0x24, 0xa9, + 0xb0, 0x53, 0x4e, 0x68, 0x0c, 0x76, 0x31, 0xb3, 0xa1, 0x00, 0x96, 0x5b, 0x19, 0x4f, 0xf3, 0x54, + 0x9d, 0xd4, 0x53, 0xab, 0x9e, 0x5a, 0xc5, 0x6c, 0xfa, 0xdd, 0xc6, 0x47, 0x0b, 0x29, 0x1e, 0x08, + 0x8d, 0x88, 0x0f, 0xf3, 0x98, 0x84, 0x89, 0x6a, 0xe0, 0x91, 0xe0, 0xd4, 0xa5, 0x01, 0x09, 0x99, + 0x1b, 0x7a, 0x1a, 0x32, 0x90, 0x39, 0x76, 0xb0, 0xe0, 0x74, 0x2e, 0xd3, 0xd2, 0x53, 0xa7, 0x78, + 0xec, 0x81, 0xc8, 0x0f, 0xa4, 0x5d, 0x91, 0xa1, 0x8c, 0x7b, 0x73, 0x86, 0x31, 0x0d, 0x08, 0x63, + 0x10, 0x4b, 0xd0, 0xa9, 0x80, 0xd2, 0x94, 0xa5, 0xa7, 0x9e, 0xe3, 0x51, 0x56, 0xff, 0xd4, 0xcd, + 0xcb, 0x0c, 0xb4, 0x6e, 0xfd, 0x85, 0xa6, 0x3d, 0x95, 0x19, 0xa8, 0x97, 0x78, 0xc2, 0x81, 0x42, + 0x58, 0x80, 0x2b, 0xe0, 0x75, 0x0d, 0x8c, 0x82, 0xd6, 0x33, 0x90, 0xd9, 0x75, 0xfe, 0x37, 0xfd, + 0xb1, 0xc9, 0xea, 0x05, 0x1e, 0x0b, 0x60, 0xde, 0xc1, 0xf5, 0x0d, 0x64, 0x76, 0x9c, 0x91, 0x8c, + 0xbf, 0xe8, 0x18, 0xf7, 0x28, 0x27, 0x22, 0xd0, 0xfe, 0x19, 0xc8, 0x1c, 0x38, 0xf5, 0x8b, 0x7a, + 0x82, 0x15, 0xe0, 0x3c, 0xe5, 0x6e, 0x22, 0x7c, 0x6d, 0x60, 0x20, 0x53, 0x71, 0x06, 0x55, 0xb8, + 0x17, 0xbe, 0x3c, 0xa8, 0x28, 0x99, 0xcb, 0x21, 0x26, 0xa5, 0xfb, 0x02, 0xa0, 0x29, 0x15, 0x18, + 0x8a, 0x92, 0x39, 0xb2, 0xdd, 0x01, 0x48, 0x43, 0x68, 0xf4, 0xc7, 0xe0, 0xda, 0x10, 0x1a, 0xed, + 0xcd, 0xed, 0xe2, 0x63, 0xab, 0xa3, 0xcd, 0x56, 0x47, 0x5f, 0x5b, 0x1d, 0xbd, 0xef, 0xf4, 0xd6, + 0x66, 0xa7, 0xb7, 0x3e, 0x77, 0x7a, 0xeb, 0xf9, 0xca, 0x0f, 0xf3, 0x60, 0xbd, 0xb2, 0x68, 0x9a, + 0xd8, 0xcd, 0xf6, 0xea, 0xc7, 0xb5, 0xf0, 0x22, 0xfb, 0x6d, 0xbf, 0x4a, 0x79, 0x47, 0x62, 0xd5, + 0xaf, 0x16, 0x79, 0xf3, 0x13, 0x00, 0x00, 0xff, 0xff, 0xec, 0xb3, 0x85, 0x18, 0xe8, 0x01, 0x00, + 0x00, } func (m *EventPackageClaim) Marshal() (dAtA []byte, err error) { @@ -183,10 +192,17 @@ func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.RelayFee) > 0 { - i -= len(m.RelayFee) - copy(dAtA[i:], m.RelayFee) - i = encodeVarintEvent(dAtA, i, uint64(len(m.RelayFee))) + if len(m.AckRelayFee) > 0 { + i -= len(m.AckRelayFee) + copy(dAtA[i:], m.AckRelayFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.AckRelayFee))) + i-- + dAtA[i] = 0x52 + } + if len(m.SynRelayFee) > 0 { + i -= len(m.SynRelayFee) + copy(dAtA[i:], m.SynRelayFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.SynRelayFee))) i-- dAtA[i] = 0x4a } @@ -282,7 +298,11 @@ func (m *EventPackageClaim) Size() (n int) { if l > 0 { n += 1 + l + sovEvent(uint64(l)) } - l = len(m.RelayFee) + l = len(m.SynRelayFee) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) + } + l = len(m.AckRelayFee) if l > 0 { n += 1 + l + sovEvent(uint64(l)) } @@ -492,7 +512,39 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 9: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RelayFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field SynRelayFee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + 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 ErrInvalidLengthEvent + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SynRelayFee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 10: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AckRelayFee", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -520,7 +572,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.RelayFee = string(dAtA[iNdEx:postIndex]) + m.AckRelayFee = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index fad8898b65..2c82d166be 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -1,6 +1,8 @@ package types import ( + "math/big" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -12,8 +14,9 @@ type StakingKeeper interface { } type CrossChainKeeper interface { - CreateRawIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte) (uint64, error) + CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, + packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, + ) (uint64, error) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication GetSrcChainID() sdk.ChainID IsDestChainSupported(chainID sdk.ChainID) bool From 172a095a8cec9a02ff95b234a7e3ccc36408eab5 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 17:12:02 +0800 Subject: [PATCH 35/50] fix unit test --- x/oracle/keeper/keeper_test.go | 3 ++- x/oracle/keeper/msg_server_test.go | 3 --- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 7a20723072..7b5d899e93 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -2,6 +2,7 @@ package keeper_test import ( "bytes" + "fmt" "testing" "time" @@ -112,7 +113,7 @@ func (s *TestSuite) TestProcessClaim() { s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp)+6, 0)) err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") - s.Require().Contains(err.Error(), "validator is not in turn") + s.Require().Contains(err.Error(), fmt.Sprintf("relayer(%s) is not in turn", validators[0].RelayerAddress)) // wrong validator set wrongValBitSet := bitset.New(256) diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index 34429cac07..5613099aad 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -115,9 +115,6 @@ func (s *TestSuite) TestInvalidClaim() { validatorMap[validator.RelayerAddress] = idx } - println("------------------") - println("relayer: ", validators[0].RelayerAddress) - msgClaim := types.MsgClaim{ FromAddress: validators[0].RelayerAddress, SrcChainId: 56, From 705c7cbd39b3cc95c1a4ee5fe23a6995b548fb13 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 20:11:59 +0800 Subject: [PATCH 36/50] distribute rewards to relayers --- proto/cosmos/oracle/v1/oracle.proto | 1 + x/oracle/keeper/keeper.go | 36 ++++++------ x/oracle/keeper/keeper_test.go | 11 ++-- x/oracle/keeper/msg_server.go | 88 ++++++++++++++++++++++------- x/oracle/keeper/msg_server_test.go | 2 + x/oracle/types/expected_keepers.go | 2 +- x/oracle/types/genesis.go | 8 +++ x/oracle/types/oracle.pb.go | 59 +++++++++++++++---- x/oracle/types/params.go | 21 +++++++ 9 files changed, 176 insertions(+), 52 deletions(-) diff --git a/proto/cosmos/oracle/v1/oracle.proto b/proto/cosmos/oracle/v1/oracle.proto index cb2d9851e5..fd18ff17bf 100644 --- a/proto/cosmos/oracle/v1/oracle.proto +++ b/proto/cosmos/oracle/v1/oracle.proto @@ -7,4 +7,5 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; message Params { uint64 relayer_timeout = 1; // in s uint64 relayer_backoff_time = 2; // in s + uint32 relayer_reward_share = 3; // in percentage } diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 85ed45e86c..ef85bcd85c 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -11,7 +11,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" "github.com/cosmos/cosmos-sdk/x/oracle/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" @@ -75,6 +74,13 @@ func (k Keeper) GetRelayerParam(ctx sdk.Context) (uint64, uint64) { return relayerTimeoutParam, relayerBackoffTimeParam } +// GetRelayerRewardShare returns the relayer reward share +func (k Keeper) GetRelayerRewardShare(ctx sdk.Context) uint32 { + var relayerRewardShare uint32 + k.paramSpace.Get(ctx, types.KeyParamRelayerRewardShare, &relayerRewardShare) + return relayerRewardShare +} + // IsRelayerInturn checks the inturn status of the relayer func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { fromAddress, err := sdk.AccAddressFromHexUnsafe(claim.FromAddress) @@ -114,58 +120,56 @@ func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Valid } // CheckClaim checks the bls signature -func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) error { +func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) ([]string, error) { historicalInfo, ok := k.StakingKeeper.GetHistoricalInfo(ctx, ctx.BlockHeight()) if !ok { - return sdkerrors.Wrapf(types.ErrValidatorSet, "get historical validators failed") + return nil, sdkerrors.Wrapf(types.ErrValidatorSet, "get historical validators failed") } validators := historicalInfo.Valset inturn, err := k.IsRelayerInturn(ctx, validators, claim) if err != nil { - return err + return nil, err } if !inturn { - return sdkerrors.Wrapf(types.ErrRelayerNotInTurn, fmt.Sprintf("relayer(%s) is not in turn", claim.FromAddress)) + return nil, sdkerrors.Wrapf(types.ErrRelayerNotInTurn, fmt.Sprintf("relayer(%s) is not in turn", claim.FromAddress)) } validatorsBitSet := bitset.From(claim.VoteAddressSet) if validatorsBitSet.Count() > uint(len(validators)) { - return sdkerrors.Wrapf(types.ErrValidatorSet, "number of validator set is larger than validators") + return nil, sdkerrors.Wrapf(types.ErrValidatorSet, "number of validator set is larger than validators") } + signedRelayers := make([]string, 0, validatorsBitSet.Count()) votedPubKeys := make([]bls.PublicKey, 0, validatorsBitSet.Count()) for index, val := range validators { if !validatorsBitSet.Test(uint(index)) { continue } + signedRelayers = append(signedRelayers, val.RelayerAddress) + votePubKey, err := bls.PublicKeyFromBytes(val.RelayerBlsKey) if err != nil { - return sdkerrors.Wrapf(types.ErrBlsPubKey, fmt.Sprintf("BLS public key converts failed: %v", err)) + return nil, sdkerrors.Wrapf(types.ErrBlsPubKey, fmt.Sprintf("BLS public key converts failed: %v", err)) } votedPubKeys = append(votedPubKeys, votePubKey) } // The valid voted validators should be no less than 2/3 validators. if len(votedPubKeys) <= len(validators)*2/3 { - return sdkerrors.Wrapf(types.ErrBlsVotesNotEnough, fmt.Sprintf("not enough validators voted, need: %d, voted: %d", len(validators)*2/3, len(votedPubKeys))) + return nil, sdkerrors.Wrapf(types.ErrBlsVotesNotEnough, fmt.Sprintf("not enough validators voted, need: %d, voted: %d", len(validators)*2/3, len(votedPubKeys))) } // Verify the aggregated signature. aggSig, err := bls.SignatureFromBytes(claim.AggSignature) if err != nil { - return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("BLS signature converts failed: %v", err)) + return nil, sdkerrors.Wrapf(types.ErrInvalidBlsSignature, fmt.Sprintf("BLS signature converts failed: %v", err)) } if !aggSig.FastAggregateVerify(votedPubKeys, claim.GetBlsSignBytes()) { - return sdkerrors.Wrapf(types.ErrInvalidBlsSignature, "signature verify failed") + return nil, sdkerrors.Wrapf(types.ErrInvalidBlsSignature, "signature verify failed") } - return nil -} - -// SendCoinsToFeeCollector transfers amt to the fee collector account. -func (k Keeper) SendCoinsToFeeCollector(ctx sdk.Context, amt sdk.Coins) error { - return k.BankKeeper.SendCoinsFromModuleToModule(ctx, crosschaintypes.ModuleName, k.feeCollectorName, amt) + return signedRelayers, nil } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 7b5d899e93..5684c56f21 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -67,6 +67,7 @@ func (s *TestSuite) TestProcessClaim() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, RelayerBackoffTime: 3, + RelayerRewardShare: 50, }) _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) @@ -106,12 +107,12 @@ func (s *TestSuite) TestProcessClaim() { msgClaim.AggSignature = blsSig s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err := s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) + _, err := s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().Nil(err, "error should be nil") // not in turn s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp)+6, 0)) - err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) + _, err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), fmt.Sprintf("relayer(%s) is not in turn", validators[0].RelayerAddress)) @@ -122,7 +123,7 @@ func (s *TestSuite) TestProcessClaim() { } msgClaim.VoteAddressSet = wrongValBitSet.Bytes() s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) + _, err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "number of validator set is larger than validators") @@ -132,7 +133,7 @@ func (s *TestSuite) TestProcessClaim() { wrongValBitSet.Set(uint(validatorMap[newValidators[1].RelayerAddress])) msgClaim.VoteAddressSet = wrongValBitSet.Bytes() s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) + _, err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "not enough validators voted") @@ -141,7 +142,7 @@ func (s *TestSuite) TestProcessClaim() { msgClaim.AggSignature = bytes.Repeat([]byte{2}, 96) s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) - err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) + _, err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().NotNil(err, "error should not be nil") s.Require().Contains(err.Error(), "BLS signature converts failed") } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index b3f996e334..cec85a5031 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -12,6 +12,7 @@ import ( "github.com/cosmos/cosmos-sdk/bsc/rlp" sdk "github.com/cosmos/cosmos-sdk/types" + crosschaintypes "github.com/cosmos/cosmos-sdk/x/crosschain/types" "github.com/cosmos/cosmos-sdk/x/oracle/types" ) @@ -49,7 +50,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", types.RelayPackagesChannelId, sequence)) } - err := k.oracleKeeper.CheckClaim(ctx, req) + signedRelayers, err := k.oracleKeeper.CheckClaim(ctx, req) if err != nil { return nil, err } @@ -61,10 +62,11 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg } events := make([]proto.Message, 0, len(packages)) + totalRelayerFee := big.NewInt(0) for idx := range packages { pack := packages[idx] - event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) + relayerFee, event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) if err != nil { // only do log, but let rest package get chance to execute. logger.Error("process package failed", "channel", pack.ChannelId, "sequence", pack.Sequence, "error", err.Error()) @@ -74,46 +76,94 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg events = append(events, event) + totalRelayerFee = totalRelayerFee.Add(totalRelayerFee, relayerFee) + // increase channel sequence k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), pack.ChannelId) } + err = distributeReward(ctx, k.oracleKeeper, req.FromAddress, signedRelayers, totalRelayerFee) + ctx.EventManager().EmitTypedEvents(events...) return &types.MsgClaimResponse{}, nil } -func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*types.EventPackageClaim, error) { +// distributeReward will distribute reward to relayers +func distributeReward(ctx sdk.Context, oracleKeeper Keeper, relayer string, signedRelayers []string, relayerFee *big.Int) error { + relayerAddr, err := sdk.AccAddressFromHexUnsafe(relayer) + if err != nil { + return sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("relayer address (%s) is invalid", relayer)) + } + + otherRelayers := make([]sdk.AccAddress, 0, len(signedRelayers)) + for idx := range signedRelayers { + signedRelayerAddr, err := sdk.AccAddressFromHexUnsafe(signedRelayers[idx]) + if err != nil { + return sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("relayer address (%s) is invalid", relayer)) + } + if !signedRelayerAddr.Equals(relayerAddr) { + otherRelayers = append(otherRelayers, relayerAddr) + } + } + + totalDistributed, otherRelayerReward := big.NewInt(0), big.NewInt(0) + + relayerRewardShare := oracleKeeper.GetRelayerRewardShare(ctx) + + // calculate the reward to distribute to each other relayer + if len(otherRelayers) > 0 { + otherRelayerReward = otherRelayerReward.Mul(big.NewInt(100-int64(relayerRewardShare)), relayerFee) + otherRelayerReward = otherRelayerReward.Div(otherRelayerReward, big.NewInt(100)) + otherRelayerReward = otherRelayerReward.Div(otherRelayerReward, big.NewInt(int64(len(otherRelayers)))) + } + + bondDenom := oracleKeeper.StakingKeeper.BondDenom(ctx) + for idx := range otherRelayers { + err = oracleKeeper.BankKeeper.SendCoinsFromModuleToAccount(ctx, + crosschaintypes.ModuleName, + otherRelayers[idx], + sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(otherRelayerReward)}}, + ) + if err != nil { + return err + } + totalDistributed = totalDistributed.Add(totalDistributed, otherRelayerReward) + } + + remainingReward := relayerFee.Sub(relayerFee, totalDistributed) + err = oracleKeeper.BankKeeper.SendCoinsFromModuleToAccount(ctx, + crosschaintypes.ModuleName, + relayerAddr, + sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(remainingReward)}}, + ) + return err +} + +func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*big.Int, *types.EventPackageClaim, error) { logger := oracleKeeper.Logger(ctx) crossChainApp := oracleKeeper.CrossChainKeeper.GetCrossChainApp(pack.ChannelId) if crossChainApp == nil { - return nil, sdkerrors.Wrapf(types.ErrChannelNotRegistered, "channel %d not registered", pack.ChannelId) + return nil, nil, sdkerrors.Wrapf(types.ErrChannelNotRegistered, "channel %d not registered", pack.ChannelId) } sequence := oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, chainId, pack.ChannelId) if sequence != pack.Sequence { - return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) } packageHeader, err := sdk.DecodePackageHeader(pack.Payload) if err != nil { - return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "payload header is invalid") + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "payload header is invalid") } if packageHeader.Timestamp != req.Timestamp { - return nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, packageHeader.Timestamp) + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, packageHeader.Timestamp) } if !sdk.IsValidCrossChainPackageType(packageHeader.PackageType) { - return nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageHeader.PackageType)) - } - - bondDenom := oracleKeeper.StakingKeeper.BondDenom(ctx) - fee := sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(packageHeader.SynRelayerFee)}} - err = oracleKeeper.SendCoinsToFeeCollector(ctx, fee) - if err != nil { - return nil, err + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageHeader.PackageType)) } cacheCtx, write := ctx.CacheContext() @@ -133,12 +183,12 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.SynPackageHeaderLength:], packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) } else { logger.Error("found payload without header", "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) - return nil, sdkerrors.Wrapf(types.ErrInvalidPackage, "payload without header") + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPackage, "payload without header") } if ibcErr != nil { logger.Error("failed to write FailAckCrossChainPackage", "err", err) - return nil, ibcErr + return nil, nil, ibcErr } sendSequence = int64(sendSeq) } else if len(result.Payload) != 0 { @@ -146,7 +196,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload, packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) if err != nil { logger.Error("failed to write AckCrossChainPackage", "err", err) - return nil, err + return nil, nil, err } sendSequence = int64(sendSeq) } @@ -165,7 +215,7 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch ErrorMsg: result.ErrMsg(), } - return claimEvent, nil + return packageHeader.SynRelayerFee, claimEvent, nil } func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, packageType sdk.CrossChainPackageType, relayerFee *big.Int) (crash bool, result sdk.ExecuteResult) { diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index 5613099aad..d8169a9d12 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -34,6 +34,7 @@ func (s *TestSuite) TestClaim() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, RelayerBackoffTime: 3, + RelayerRewardShare: 50, }) _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) @@ -99,6 +100,7 @@ func (s *TestSuite) TestInvalidClaim() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, RelayerBackoffTime: 3, + RelayerRewardShare: 50, }) _, _, newValidators, blsKeys := createValidators(s.T(), s.ctx, s.app, []int64{9, 8, 7}) diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 2c82d166be..c6b339dac8 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -25,5 +25,5 @@ type CrossChainKeeper interface { } type BankKeeper interface { - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error } diff --git a/x/oracle/types/genesis.go b/x/oracle/types/genesis.go index d0add40862..55859a5001 100644 --- a/x/oracle/types/genesis.go +++ b/x/oracle/types/genesis.go @@ -29,5 +29,13 @@ func ValidateGenesis(data GenesisState) error { if data.Params.RelayerBackoffTime <= 0 { return fmt.Errorf("the relayer backoff time must be positive, is %d", data.Params.RelayerBackoffTime) } + + if data.Params.RelayerRewardShare <= 0 { + return fmt.Errorf("the relayer reward share must be positive, is %d", data.Params.RelayerRewardShare) + } + + if data.Params.RelayerRewardShare > 100 { + return fmt.Errorf("the relayer reward share should not be larger than 100, is %d", data.Params.RelayerRewardShare) + } return nil } diff --git a/x/oracle/types/oracle.pb.go b/x/oracle/types/oracle.pb.go index 7b48f9cb78..91ea45332a 100644 --- a/x/oracle/types/oracle.pb.go +++ b/x/oracle/types/oracle.pb.go @@ -26,6 +26,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Params struct { RelayerTimeout uint64 `protobuf:"varint,1,opt,name=relayer_timeout,json=relayerTimeout,proto3" json:"relayer_timeout,omitempty"` RelayerBackoffTime uint64 `protobuf:"varint,2,opt,name=relayer_backoff_time,json=relayerBackoffTime,proto3" json:"relayer_backoff_time,omitempty"` + RelayerRewardShare uint32 `protobuf:"varint,3,opt,name=relayer_reward_share,json=relayerRewardShare,proto3" json:"relayer_reward_share,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -75,6 +76,13 @@ func (m *Params) GetRelayerBackoffTime() uint64 { return 0 } +func (m *Params) GetRelayerRewardShare() uint32 { + if m != nil { + return m.RelayerRewardShare + } + return 0 +} + func init() { proto.RegisterType((*Params)(nil), "cosmos.oracle.v1.Params") } @@ -82,19 +90,21 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/oracle.proto", fileDescriptor_3dec273964b5043c) } var fileDescriptor_3dec273964b5043c = []byte{ - // 190 bytes of a gzipped FileDescriptorProto + // 219 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0x84, 0xb2, 0xf4, 0x0a, - 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0xa5, 0x64, 0x2e, - 0xb6, 0x80, 0xc4, 0xa2, 0xc4, 0xdc, 0x62, 0x21, 0x75, 0x2e, 0xfe, 0xa2, 0xd4, 0x9c, 0xc4, 0xca, - 0xd4, 0xa2, 0xf8, 0x92, 0xcc, 0xdc, 0xd4, 0xfc, 0xd2, 0x12, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x96, - 0x20, 0x3e, 0xa8, 0x70, 0x08, 0x44, 0x54, 0xc8, 0x80, 0x4b, 0x04, 0xa6, 0x30, 0x29, 0x31, 0x39, - 0x3b, 0x3f, 0x2d, 0x0d, 0xac, 0x41, 0x82, 0x09, 0xac, 0x5a, 0x08, 0x2a, 0xe7, 0x04, 0x91, 0x02, - 0x69, 0x72, 0x72, 0x3d, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, - 0x27, 0x3c, 0x96, 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xed, 0xf4, - 0xcc, 0x92, 0x8c, 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, 0xd3, 0x21, 0x94, 0x6e, 0x71, - 0x4a, 0xb6, 0x7e, 0x05, 0xcc, 0x1f, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0x4f, 0x18, - 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x77, 0x36, 0xc0, 0xd0, 0xe5, 0x00, 0x00, 0x00, + 0x8a, 0xf2, 0x4b, 0xf2, 0x85, 0x04, 0x20, 0xd2, 0x7a, 0x50, 0xc1, 0x32, 0x43, 0xa5, 0xa9, 0x8c, + 0x5c, 0x6c, 0x01, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x42, 0xea, 0x5c, 0xfc, 0x45, 0xa9, 0x39, 0x89, + 0x95, 0xa9, 0x45, 0xf1, 0x25, 0x99, 0xb9, 0xa9, 0xf9, 0xa5, 0x25, 0x12, 0x8c, 0x0a, 0x8c, 0x1a, + 0x2c, 0x41, 0x7c, 0x50, 0xe1, 0x10, 0x88, 0xa8, 0x90, 0x01, 0x97, 0x08, 0x4c, 0x61, 0x52, 0x62, + 0x72, 0x76, 0x7e, 0x5a, 0x1a, 0x58, 0x83, 0x04, 0x13, 0x58, 0xb5, 0x10, 0x54, 0xce, 0x09, 0x22, + 0x05, 0xd2, 0x84, 0xac, 0xa3, 0x28, 0xb5, 0x3c, 0xb1, 0x28, 0x25, 0xbe, 0x38, 0x23, 0xb1, 0x28, + 0x55, 0x82, 0x59, 0x81, 0x51, 0x83, 0x17, 0xae, 0x23, 0x08, 0x2c, 0x15, 0x0c, 0x92, 0x71, 0x72, + 0x3d, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, 0x18, 0x27, 0x3c, 0x96, + 0x63, 0xb8, 0xf0, 0x58, 0x8e, 0xe1, 0xc6, 0x63, 0x39, 0x86, 0x28, 0xed, 0xf4, 0xcc, 0x92, 0x8c, + 0xd2, 0x24, 0xbd, 0xe4, 0xfc, 0x5c, 0x7d, 0xa8, 0x6f, 0x21, 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, + 0x05, 0xcc, 0xeb, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0x7f, 0x1b, 0x03, 0x02, 0x00, + 0x00, 0xff, 0xff, 0xcc, 0x35, 0x86, 0x1a, 0x18, 0x01, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -117,6 +127,11 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if m.RelayerRewardShare != 0 { + i = encodeVarintOracle(dAtA, i, uint64(m.RelayerRewardShare)) + i-- + dAtA[i] = 0x18 + } if m.RelayerBackoffTime != 0 { i = encodeVarintOracle(dAtA, i, uint64(m.RelayerBackoffTime)) i-- @@ -153,6 +168,9 @@ func (m *Params) Size() (n int) { if m.RelayerBackoffTime != 0 { n += 1 + sovOracle(uint64(m.RelayerBackoffTime)) } + if m.RelayerRewardShare != 0 { + n += 1 + sovOracle(uint64(m.RelayerRewardShare)) + } return n } @@ -229,6 +247,25 @@ func (m *Params) Unmarshal(dAtA []byte) error { break } } + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field RelayerRewardShare", wireType) + } + m.RelayerRewardShare = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowOracle + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.RelayerRewardShare |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipOracle(dAtA[iNdEx:]) diff --git a/x/oracle/types/params.go b/x/oracle/types/params.go index 96c3c9998e..3be3d6c3ec 100644 --- a/x/oracle/types/params.go +++ b/x/oracle/types/params.go @@ -9,17 +9,20 @@ import ( const ( DefaultRelayerTimeout uint64 = 40 // in s DefaultRelayerBackoffTime uint64 = 5 // in s + DefaultRelayerRewardShare uint32 = 50 // in s ) var ( KeyParamRelayerTimeout = []byte("RelayerTimeout") KeyParamRelayerBackoffTime = []byte("RelayerBackoffTime") + KeyParamRelayerRewardShare = []byte("RelayerRewardShare") ) func DefaultParams() Params { return Params{ RelayerTimeout: DefaultRelayerTimeout, RelayerBackoffTime: DefaultRelayerBackoffTime, + RelayerRewardShare: DefaultRelayerRewardShare, } } @@ -32,6 +35,7 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { return paramtypes.ParamSetPairs{ paramtypes.NewParamSetPair(KeyParamRelayerTimeout, p.RelayerTimeout, validateRelayerTimeout), paramtypes.NewParamSetPair(KeyParamRelayerBackoffTime, p.RelayerBackoffTime, validateRelayerBackoffTime), + paramtypes.NewParamSetPair(KeyParamRelayerRewardShare, p.RelayerRewardShare, validateRelayerRewardShare), } } @@ -60,3 +64,20 @@ func validateRelayerBackoffTime(i interface{}) error { return nil } + +func validateRelayerRewardShare(i interface{}) error { + v, ok := i.(uint32) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + if v <= 0 { + return fmt.Errorf("the relayer reward share should be positive: %d", v) + } + + if v > 100 { + return fmt.Errorf("the relayer reward share should not be larger than 100") + } + + return nil +} From 98471dddb4eb59366e216ed9e82d563afe7eba35 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Tue, 10 Jan 2023 20:36:26 +0800 Subject: [PATCH 37/50] remove unused param --- proto/cosmos/crosschain/v1/crosschain.proto | 1 - x/crosschain/keeper/keeper.go | 11 ---- x/crosschain/types/crosschain.pb.go | 67 +++------------------ x/crosschain/types/genesis.go | 18 +----- x/crosschain/types/params.go | 37 +----------- x/oracle/keeper/keeper_test.go | 1 + 6 files changed, 11 insertions(+), 124 deletions(-) diff --git a/proto/cosmos/crosschain/v1/crosschain.proto b/proto/cosmos/crosschain/v1/crosschain.proto index fab7080458..0a86e92f82 100644 --- a/proto/cosmos/crosschain/v1/crosschain.proto +++ b/proto/cosmos/crosschain/v1/crosschain.proto @@ -5,5 +5,4 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; // Params holds parameters for the cross chain module. message Params { - string relayer_fee = 1; } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 50784a6170..b32654b746 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -51,17 +51,6 @@ func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { k.SetParams(ctx, state.Params) } -// GetRelayerFeeParam returns the default relayer fee for cross chain tx -func (k Keeper) GetRelayerFeeParam(ctx sdk.Context) *big.Int { - var relayerFeeParam string - k.paramSpace.Get(ctx, types.KeyParamRelayerFee, &relayerFeeParam) - relayerFee, valid := big.NewInt(0).SetString(relayerFeeParam, 10) - if !valid { - panic(fmt.Errorf("invalid relayer fee: %s", relayerFeeParam)) - } - return relayerFee -} - // SetParams sets the params of cross chain module func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { k.paramSpace.SetParamSet(ctx, ¶ms) diff --git a/x/crosschain/types/crosschain.pb.go b/x/crosschain/types/crosschain.pb.go index 445f7aded3..98aff874ae 100644 --- a/x/crosschain/types/crosschain.pb.go +++ b/x/crosschain/types/crosschain.pb.go @@ -24,7 +24,6 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the cross chain module. type Params struct { - RelayerFee string `protobuf:"bytes,1,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -60,13 +59,6 @@ func (m *Params) XXX_DiscardUnknown() { var xxx_messageInfo_Params proto.InternalMessageInfo -func (m *Params) GetRelayerFee() string { - if m != nil { - return m.RelayerFee - } - return "" -} - func init() { proto.RegisterType((*Params)(nil), "cosmos.crosschain.v1.Params") } @@ -76,18 +68,16 @@ func init() { } var fileDescriptor_d7b94a7254cf916a = []byte{ - // 164 bytes of a gzipped FileDescriptorProto + // 136 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, 0x44, 0xe2, 0xe9, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x89, 0x40, 0x94, 0xe9, 0x21, 0x49, 0x94, - 0x19, 0x2a, 0x69, 0x72, 0xb1, 0x05, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x0b, 0xc9, 0x73, 0x71, 0x17, - 0xa5, 0xe6, 0x24, 0x56, 0xa6, 0x16, 0xc5, 0xa7, 0xa5, 0xa6, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, - 0x06, 0x71, 0x41, 0x85, 0xdc, 0x52, 0x53, 0x9d, 0x3c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, - 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, - 0x58, 0x8e, 0x21, 0x4a, 0x3f, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, - 0xe6, 0x18, 0x30, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0xec, 0xb2, 0x92, 0xca, 0x82, 0xd4, - 0xe2, 0x24, 0x36, 0xb0, 0x93, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x9a, 0x72, 0xe2, 0x66, - 0xbb, 0x00, 0x00, 0x00, + 0x19, 0x2a, 0x71, 0x70, 0xb1, 0x05, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x3b, 0x79, 0x9e, 0x78, 0x24, + 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, + 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x7e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, + 0x72, 0x7e, 0xae, 0x3e, 0xcc, 0x2e, 0x30, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0x6c, 0x71, + 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x46, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, + 0xde, 0xa5, 0xe0, 0xba, 0x9a, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -110,13 +100,6 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.RelayerFee) > 0 { - i -= len(m.RelayerFee) - copy(dAtA[i:], m.RelayerFee) - i = encodeVarintCrosschain(dAtA, i, uint64(len(m.RelayerFee))) - i-- - dAtA[i] = 0xa - } return len(dAtA) - i, nil } @@ -137,10 +120,6 @@ func (m *Params) Size() (n int) { } var l int _ = l - l = len(m.RelayerFee) - if l > 0 { - n += 1 + l + sovCrosschain(uint64(l)) - } return n } @@ -179,38 +158,6 @@ func (m *Params) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field RelayerFee", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowCrosschain - } - 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 ErrInvalidLengthCrosschain - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthCrosschain - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.RelayerFee = string(dAtA[iNdEx:postIndex]) - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCrosschain(dAtA[iNdEx:]) diff --git a/x/crosschain/types/genesis.go b/x/crosschain/types/genesis.go index 1f418457fa..99947edb7e 100644 --- a/x/crosschain/types/genesis.go +++ b/x/crosschain/types/genesis.go @@ -1,10 +1,5 @@ package types -import ( - "fmt" - "math/big" -) - // NewGenesisState creates a new GenesisState object func NewGenesisState( params Params, @@ -21,18 +16,7 @@ func DefaultGenesisState() *GenesisState { } } -// ValidateGenesis validates the slashing genesis parameters +// ValidateGenesis validates the cross chain genesis parameters func ValidateGenesis(data GenesisState) error { - relayerFee := big.NewInt(0) - relayerFee, valid := relayerFee.SetString(data.Params.RelayerFee, 10) - - if !valid { - return fmt.Errorf("invalid relayer fee, is %s", data.Params.RelayerFee) - } - - if relayerFee.Cmp(big.NewInt(0)) < 0 { - return fmt.Errorf("relayer fee should not be negative, is %s", data.Params.RelayerFee) - } - return nil } diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 7440cc7cfb..54ca1b2d2f 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -1,22 +1,11 @@ package types import ( - "fmt" - "math/big" - paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -const ( - DefaultRelayerFeeParam string = "1" -) - -var KeyParamRelayerFee = []byte("RelayerFee") - func DefaultParams() Params { - return Params{ - RelayerFee: DefaultRelayerFeeParam, - } + return Params{} } func ParamKeyTable() paramtypes.KeyTable { @@ -25,27 +14,5 @@ func ParamKeyTable() paramtypes.KeyTable { // ParamSetPairs implements params.ParamSet func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{ - paramtypes.NewParamSetPair(KeyParamRelayerFee, p.RelayerFee, validateRelayerFee), - } -} - -func validateRelayerFee(i interface{}) error { - v, ok := i.(string) - if !ok { - return fmt.Errorf("invalid parameter type: %T", i) - } - - relayerFee := big.NewInt(0) - relayerFee, valid := relayerFee.SetString(v, 10) - - if !valid { - return fmt.Errorf("invalid relayer fee, %s", v) - } - - if relayerFee.Cmp(big.NewInt(0)) < 0 { - return fmt.Errorf("invalid relayer fee, %s", v) - } - - return nil + return paramtypes.ParamSetPairs{} } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 5684c56f21..95e03c96ea 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -151,6 +151,7 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, RelayerBackoffTime: 3, + RelayerRewardShare: 50, }) vals := make([]stakingtypes.Validator, 5) From f52d32307e1034ed943ffa0401db3b7e3a7fc6ec Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 11 Jan 2023 11:27:44 +0800 Subject: [PATCH 38/50] mint initial balance to cross chain module --- proto/cosmos/crosschain/v1/crosschain.proto | 1 + simapp/app.go | 2 +- types/cross_chain.go | 8 +-- x/crosschain/keeper/config.go | 12 ++-- x/crosschain/keeper/keeper.go | 53 ++++++++++------ x/crosschain/keeper/keeper_test.go | 12 ---- x/crosschain/module.go | 10 ++- x/crosschain/types/crosschain.pb.go | 67 ++++++++++++++++++--- x/crosschain/types/expected_keepers.go | 13 ++++ x/crosschain/types/params.go | 33 +++++++++- x/oracle/keeper/keeper_test.go | 1 + x/oracle/keeper/msg_server_test.go | 5 +- 12 files changed, 157 insertions(+), 60 deletions(-) create mode 100644 x/crosschain/types/expected_keepers.go diff --git a/proto/cosmos/crosschain/v1/crosschain.proto b/proto/cosmos/crosschain/v1/crosschain.proto index 0a86e92f82..222197305a 100644 --- a/proto/cosmos/crosschain/v1/crosschain.proto +++ b/proto/cosmos/crosschain/v1/crosschain.proto @@ -5,4 +5,5 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; // Params holds parameters for the cross chain module. message Params { + string init_module_balance = 1; } diff --git a/simapp/app.go b/simapp/app.go index 823aa48b4b..bfe3213f57 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -146,7 +146,7 @@ var ( stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, nft.ModuleName: nil, - crosschaintypes.ModuleName: nil, + crosschaintypes.ModuleName: {authtypes.Minter}, } ) diff --git a/types/cross_chain.go b/types/cross_chain.go index adeed33cf0..a2404043a1 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -72,13 +72,11 @@ func GetPackageHeaderLength(packageType CrossChainPackageType) int { type PackageHeader struct { PackageType CrossChainPackageType Timestamp uint64 - SynRelayerFee *big.Int - AckRelayerFee *big.Int + SynRelayerFee *big.Int // syn relayer fee is the relayer fee paid to relayer src source chain to dest chain + AckRelayerFee *big.Int // ack relayer fee is the relayer fee paid to relayer for the ack or fail ack package if there is any } -var ( - NilAckRelayerFee = big.NewInt(0) // For ack packages, the ack relayer fee should be nil, and it would not be encoded into package header -) +var NilAckRelayerFee = big.NewInt(0) // For ack packages, the ack relayer fee should be nil, and it would not be encoded into package header func EncodePackageHeader(header PackageHeader) []byte { packageHeader := make([]byte, GetPackageHeaderLength(header.PackageType)) diff --git a/x/crosschain/keeper/config.go b/x/crosschain/keeper/config.go index 53348aa8ff..a26c8dc750 100644 --- a/x/crosschain/keeper/config.go +++ b/x/crosschain/keeper/config.go @@ -3,10 +3,8 @@ package keeper import sdk "github.com/cosmos/cosmos-sdk/types" type crossChainConfig struct { - srcChainID sdk.ChainID - - destChains []sdk.ChainID - + srcChainID sdk.ChainID + destChainId sdk.ChainID nameToChannelID map[string]sdk.ChannelID channelIDToName map[sdk.ChannelID]string channelIDToApp map[sdk.ChannelID]sdk.CrossChainApplication @@ -14,10 +12,8 @@ type crossChainConfig struct { func newCrossChainCfg() *crossChainConfig { config := &crossChainConfig{ - srcChainID: 0, - - destChains: make([]sdk.ChainID, 0), - + srcChainID: 0, + destChainId: 0, nameToChannelID: make(map[string]sdk.ChannelID), channelIDToName: make(map[sdk.ChannelID]string), channelIDToApp: make(map[sdk.ChannelID]sdk.CrossChainApplication), diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index b32654b746..7aa463e53a 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -46,9 +46,31 @@ func (k Keeper) Logger(ctx sdk.Context) log.Logger { } // InitGenesis inits the genesis state of cross chain module -func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState) { +func (k Keeper) InitGenesis(ctx sdk.Context, state *types.GenesisState, bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper) { k.Logger(ctx).Info("set cross chain genesis state", "params", state.Params.String()) k.SetParams(ctx, state.Params) + + initModuleBalance := k.GetInitModuleBalance(ctx) + bondDenom := stakingKeeper.BondDenom(ctx) + + err := bankKeeper.MintCoins(ctx, types.ModuleName, sdk.Coins{sdk.Coin{ + Denom: bondDenom, + Amount: sdk.NewIntFromBigInt(initModuleBalance), + }}) + if err != nil { + panic(fmt.Sprintf("mint initial cross chain module balance error, err=%s", err.Error())) + } +} + +// GetInitModuleBalance returns the initial balance of cross chain module +func (k Keeper) GetInitModuleBalance(ctx sdk.Context) *big.Int { + var initModuleBlaanceParam string + k.paramSpace.Get(ctx, types.KeyParamInitModuleBalance, &initModuleBlaanceParam) + moduleBalance, valid := big.NewInt(0).SetString(initModuleBlaanceParam, 10) + if !valid { + panic(fmt.Errorf("invalid init module balance: %s", initModuleBlaanceParam)) + } + return moduleBalance } // SetParams sets the params of cross chain module @@ -119,26 +141,9 @@ func (k Keeper) RegisterChannel(name string, id sdk.ChannelID, app sdk.CrossChai return nil } -// RegisterDestChain registers a dest chain -func (k Keeper) RegisterDestChain(chainID sdk.ChainID) error { - for _, chain := range k.cfg.destChains { - if chainID == chain { - return fmt.Errorf("duplicated destination chain chainID") - } - } - - k.cfg.destChains = append(k.cfg.destChains, chainID) - return nil -} - // IsDestChainSupported returns the support status of a dest chain func (k Keeper) IsDestChainSupported(chainID sdk.ChainID) bool { - for _, chain := range k.cfg.destChains { - if chainID == chain { - return true - } - } - return false + return chainID == k.cfg.destChainId } // SetChannelSendPermission sets the channel send permission @@ -167,6 +172,16 @@ func (k Keeper) GetSrcChainID() sdk.ChainID { return k.cfg.srcChainID } +// SetDestChainID sets the destination chain id +func (k Keeper) SetDestChainID(destChainId sdk.ChainID) { + k.cfg.destChainId = destChainId +} + +// GetDestChainID gets the destination chain id +func (k Keeper) GetDestChainID() sdk.ChainID { + return k.cfg.destChainId +} + // GetIBCPackage returns the ibc package by sequence func (k Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { kvStore := ctx.KVStore(k.storeKey) diff --git a/x/crosschain/keeper/keeper_test.go b/x/crosschain/keeper/keeper_test.go index 9940a14e33..90d41aa043 100644 --- a/x/crosschain/keeper/keeper_test.go +++ b/x/crosschain/keeper/keeper_test.go @@ -55,18 +55,6 @@ func (s *TestSuite) TestIncrReceiveSequence() { s.Require().EqualValues(afterSequence, beforeSequence+1) } -func (s *TestSuite) TestRegisterDestChain() { - testChainId := sdk.ChainID(100) - - err := s.app.CrossChainKeeper.RegisterDestChain(testChainId) - - s.Require().NoError(err) - - // check duplicate channel id - err = s.app.CrossChainKeeper.RegisterDestChain(testChainId) - s.Require().ErrorContains(err, "duplicated destination chain chainID") -} - func (s *TestSuite) TestRegisterChannel() { testChannelName := "test channel" testChannelId := sdk.ChannelID(100) diff --git a/x/crosschain/module.go b/x/crosschain/module.go index 4cdf0f85b7..05d244d00c 100644 --- a/x/crosschain/module.go +++ b/x/crosschain/module.go @@ -75,14 +75,18 @@ func (am AppModuleBasic) RegisterInterfaces(registry codectypes.InterfaceRegistr type AppModule struct { AppModuleBasic - keeper keeper.Keeper + keeper keeper.Keeper + bankKeeper types.BankKeeper + stakingKeeper types.StakingKeeper } // NewAppModule creates a new AppModule object -func NewAppModule(k keeper.Keeper) AppModule { +func NewAppModule(k keeper.Keeper, bankKeeper types.BankKeeper, stakingKeeper types.StakingKeeper) AppModule { return AppModule{ AppModuleBasic: AppModuleBasic{}, keeper: k, + bankKeeper: bankKeeper, + stakingKeeper: stakingKeeper, } } @@ -92,7 +96,7 @@ func (am AppModule) RegisterInvariants(_ sdk.InvariantRegistry) {} func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) []abci.ValidatorUpdate { var genesisState types.GenesisState cdc.MustUnmarshalJSON(data, &genesisState) - am.keeper.InitGenesis(ctx, &genesisState) + am.keeper.InitGenesis(ctx, &genesisState, am.bankKeeper, am.stakingKeeper) return []abci.ValidatorUpdate{} } diff --git a/x/crosschain/types/crosschain.pb.go b/x/crosschain/types/crosschain.pb.go index 98aff874ae..9e3e1bbd23 100644 --- a/x/crosschain/types/crosschain.pb.go +++ b/x/crosschain/types/crosschain.pb.go @@ -24,6 +24,7 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // Params holds parameters for the cross chain module. type Params struct { + InitModuleBalance string `protobuf:"bytes,1,opt,name=init_module_balance,json=initModuleBalance,proto3" json:"init_module_balance,omitempty"` } func (m *Params) Reset() { *m = Params{} } @@ -59,6 +60,13 @@ func (m *Params) XXX_DiscardUnknown() { var xxx_messageInfo_Params proto.InternalMessageInfo +func (m *Params) GetInitModuleBalance() string { + if m != nil { + return m.InitModuleBalance + } + return "" +} + func init() { proto.RegisterType((*Params)(nil), "cosmos.crosschain.v1.Params") } @@ -68,16 +76,18 @@ func init() { } var fileDescriptor_d7b94a7254cf916a = []byte{ - // 136 bytes of a gzipped FileDescriptorProto + // 175 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x4d, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, 0x44, 0xe2, 0xe9, 0x15, 0x14, 0xe5, 0x97, 0xe4, 0x0b, 0x89, 0x40, 0x94, 0xe9, 0x21, 0x49, 0x94, - 0x19, 0x2a, 0x71, 0x70, 0xb1, 0x05, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x3b, 0x79, 0x9e, 0x78, 0x24, - 0xc7, 0x78, 0xe1, 0x91, 0x1c, 0xe3, 0x83, 0x47, 0x72, 0x8c, 0x13, 0x1e, 0xcb, 0x31, 0x5c, 0x78, - 0x2c, 0xc7, 0x70, 0xe3, 0xb1, 0x1c, 0x43, 0x94, 0x7e, 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, - 0x72, 0x7e, 0xae, 0x3e, 0xcc, 0x2e, 0x30, 0xa5, 0x5b, 0x9c, 0x92, 0xad, 0x5f, 0x81, 0x6c, 0x71, - 0x49, 0x65, 0x41, 0x6a, 0x71, 0x12, 0x1b, 0xd8, 0x46, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xde, 0xa5, 0xe0, 0xba, 0x9a, 0x00, 0x00, 0x00, + 0x19, 0x2a, 0x59, 0x70, 0xb1, 0x05, 0x24, 0x16, 0x25, 0xe6, 0x16, 0x0b, 0xe9, 0x71, 0x09, 0x67, + 0xe6, 0x65, 0x96, 0xc4, 0xe7, 0xe6, 0xa7, 0x94, 0xe6, 0xa4, 0xc6, 0x27, 0x25, 0xe6, 0x24, 0xe6, + 0x25, 0xa7, 0x4a, 0x30, 0x2a, 0x30, 0x6a, 0x70, 0x06, 0x09, 0x82, 0xa4, 0x7c, 0xc1, 0x32, 0x4e, + 0x10, 0x09, 0x27, 0xcf, 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, 0x4f, + 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x87, 0xb9, 0x0d, 0x4c, 0xe9, 0x16, + 0xa7, 0x64, 0xeb, 0x57, 0x20, 0x3b, 0xb4, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0xec, 0x42, + 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xe6, 0x93, 0xeb, 0xca, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { @@ -100,6 +110,13 @@ func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.InitModuleBalance) > 0 { + i -= len(m.InitModuleBalance) + copy(dAtA[i:], m.InitModuleBalance) + i = encodeVarintCrosschain(dAtA, i, uint64(len(m.InitModuleBalance))) + i-- + dAtA[i] = 0xa + } return len(dAtA) - i, nil } @@ -120,6 +137,10 @@ func (m *Params) Size() (n int) { } var l int _ = l + l = len(m.InitModuleBalance) + if l > 0 { + n += 1 + l + sovCrosschain(uint64(l)) + } return n } @@ -158,6 +179,38 @@ func (m *Params) Unmarshal(dAtA []byte) error { return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitModuleBalance", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowCrosschain + } + 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 ErrInvalidLengthCrosschain + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthCrosschain + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitModuleBalance = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipCrosschain(dAtA[iNdEx:]) diff --git a/x/crosschain/types/expected_keepers.go b/x/crosschain/types/expected_keepers.go new file mode 100644 index 0000000000..d2e3612e4d --- /dev/null +++ b/x/crosschain/types/expected_keepers.go @@ -0,0 +1,13 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) + +type BankKeeper interface { + MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error +} + +type StakingKeeper interface { + BondDenom(ctx sdk.Context) (res string) +} diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 54ca1b2d2f..9ec046504a 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -1,11 +1,20 @@ package types import ( + "fmt" + "math/big" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) +const DefaultInitModuleBalance string = "1000000000" + +var KeyParamInitModuleBalance = []byte("InitModuleBalance") + func DefaultParams() Params { - return Params{} + return Params{ + InitModuleBalance: DefaultInitModuleBalance, + } } func ParamKeyTable() paramtypes.KeyTable { @@ -14,5 +23,25 @@ func ParamKeyTable() paramtypes.KeyTable { // ParamSetPairs implements params.ParamSet func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { - return paramtypes.ParamSetPairs{} + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(KeyParamInitModuleBalance, p.InitModuleBalance, validateInitModuleBalance), + } +} + +func validateInitModuleBalance(i interface{}) error { + v, ok := i.(string) + if !ok { + return fmt.Errorf("invalid parameter type: %T", i) + } + + balance, valid := big.NewInt(0).SetString(v, 10) + if !valid { + return fmt.Errorf("invalid module balance, is %s", v) + } + + if balance.Cmp(big.NewInt(0)) < 0 { + return fmt.Errorf("init module balance should be positive, is %s", v) + } + + return nil } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 95e03c96ea..3f64cbc143 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -49,6 +49,7 @@ func (s *TestSuite) SetupTest() { s.ctx = ctx s.app.CrossChainKeeper.SetSrcChainID(sdk.ChainID(1)) + s.app.CrossChainKeeper.SetDestChainID(sdk.ChainID(56)) coins := sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(100000))) err := s.app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, coins) diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index d8169a9d12..a935487a68 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -29,7 +29,6 @@ func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, payload []b func (s *TestSuite) TestClaim() { s.app.CrossChainKeeper.RegisterChannel("test", sdk.ChannelID(1), &DummyCrossChainApp{}) - s.app.CrossChainKeeper.RegisterDestChain(sdk.ChainID(56)) s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, @@ -119,7 +118,7 @@ func (s *TestSuite) TestInvalidClaim() { msgClaim := types.MsgClaim{ FromAddress: validators[0].RelayerAddress, - SrcChainId: 56, + SrcChainId: 65, DestChainId: 1, Sequence: 0, Timestamp: 1992, @@ -145,7 +144,7 @@ func (s *TestSuite) TestInvalidClaim() { s.Require().NotNil(err, "process claim should return error") s.Require().Contains(err.Error(), "src chain id is invalid") - s.app.CrossChainKeeper.RegisterDestChain(sdk.ChainID(56)) + s.app.CrossChainKeeper.SetDestChainID(sdk.ChainID(65)) // invalid payload s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp), 0)) From 86bb4d2980b129c2c0679bdd467fd71c735a9884 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 11 Jan 2023 15:14:43 +0800 Subject: [PATCH 39/50] add rpc queries for cross chain module --- proto/cosmos/crosschain/v1/query.proto | 50 +- proto/cosmos/oracle/v1/query.proto | 17 + x/crosschain/keeper/grpc_query.go | 35 +- x/crosschain/keeper/keeper.go | 34 +- x/crosschain/keeper/keeper_test.go | 12 +- x/crosschain/keeper/querier.go | 33 - x/crosschain/module.go | 2 +- x/crosschain/types/keys.go | 2 +- x/crosschain/types/query.pb.go | 1202 +++++++++++++++++++++++- x/crosschain/types/query.pb.gw.go | 249 +++++ x/oracle/keeper/grpc_query.go | 7 + x/oracle/keeper/grpc_query_params.go | 20 + x/oracle/keeper/keeper.go | 6 + x/oracle/keeper/msg_server.go | 43 +- x/oracle/keeper/querier.go | 17 - x/oracle/module.go | 2 +- x/oracle/types/expected_keepers.go | 6 +- x/oracle/types/query.pb.go | 474 +++++++++- x/oracle/types/query.pb.gw.go | 153 +++ 19 files changed, 2213 insertions(+), 151 deletions(-) delete mode 100644 x/crosschain/keeper/querier.go create mode 100644 x/oracle/keeper/grpc_query.go create mode 100644 x/oracle/keeper/grpc_query_params.go delete mode 100644 x/oracle/keeper/querier.go create mode 100644 x/oracle/types/query.pb.gw.go diff --git a/proto/cosmos/crosschain/v1/query.proto b/proto/cosmos/crosschain/v1/query.proto index a6fe71c2ca..b5a5086448 100644 --- a/proto/cosmos/crosschain/v1/query.proto +++ b/proto/cosmos/crosschain/v1/query.proto @@ -9,10 +9,25 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/crosschain/types"; // Query provides defines the gRPC querier service. service Query { - // Params returns the total set of minting parameters. + // Params returns the total set of cross chain parameters. rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { option (google.api.http).get = "/cosmos/crosschain/v1/params"; } + + // CrossChainPackage returns the specified cross chain package + rpc CrossChainPackage(QueryCrossChainPackageRequest) returns (QueryCrossChainPackageResponse) { + option (google.api.http).get = "/cosmos/crosschain/v1/cross_chain_package"; + } + + // SendSequence returns the send sequence of the channel + rpc SendSequence(QuerySendSequenceRequest) returns (QuerySendSequenceResponse) { + option (google.api.http).get = "/cosmos/crosschain/v1/send_sequence"; + } + + // ReceiveSequence returns the receive sequence of the channel + rpc ReceiveSequence(QueryReceiveSequenceRequest) returns (QueryReceiveSequenceResponse) { + option (google.api.http).get = "/cosmos/crosschain/v1/receive_sequence"; + } } // QueryParamsRequest is the request type for the Query/Params RPC method. @@ -22,4 +37,35 @@ message QueryParamsRequest {} message QueryParamsResponse { // params defines the parameters of the module. Params params = 1 [(gogoproto.nullable) = false]; -} \ No newline at end of file +} + +// QueryCrossChainPackageRequest is the request type for the Query/CrossChainPackage RPC method. +message QueryCrossChainPackageRequest { + uint32 channel_id = 1; + uint64 sequence = 2; +} + +// QueryCrossChainPackageResponse is the response type for the Query/CrossChainPackage RPC method. +message QueryCrossChainPackageResponse { + bytes package = 1; +} + +// QuerySendSequenceRequest is the request type for the Query/SendSequence RPC method. +message QuerySendSequenceRequest { + uint32 channel_id = 1; +} + +// QuerySendSequenceResponse is the response type for the Query/SendSequence RPC method. +message QuerySendSequenceResponse { + uint64 sequence = 1; +} + +// QuerySendSequenceRequest is the request type for the Query/ReceiveSequence RPC method. +message QueryReceiveSequenceRequest { + uint32 channel_id = 1; +} + +// QuerySendSequenceResponse is the response type for the Query/ReceiveSequence RPC method. +message QueryReceiveSequenceResponse { + uint64 sequence = 1; +} diff --git a/proto/cosmos/oracle/v1/query.proto b/proto/cosmos/oracle/v1/query.proto index 22f9c63aaf..dd6cc191a9 100644 --- a/proto/cosmos/oracle/v1/query.proto +++ b/proto/cosmos/oracle/v1/query.proto @@ -1,8 +1,25 @@ syntax = "proto3"; package cosmos.oracle.v1; +import "gogoproto/gogo.proto"; +import "google/api/annotations.proto"; +import "cosmos/oracle/v1/oracle.proto"; + option go_package = "github.com/cosmos/cosmos-sdk/x/oracle/types"; // Query provides defines the gRPC querier service. service Query { + // Params returns the total set of cross chain parameters. + rpc Params(QueryParamsRequest) returns (QueryParamsResponse) { + option (google.api.http).get = "/cosmos/oracle/v1/params"; + } } + +// QueryParamsRequest is the request type for the Query/Params RPC method. +message QueryParamsRequest {} + +// QueryParamsResponse is the response type for the Query/Params RPC method. +message QueryParamsResponse { + // params defines the parameters of the module. + Params params = 1 [(gogoproto.nullable) = false]; +} \ No newline at end of file diff --git a/x/crosschain/keeper/grpc_query.go b/x/crosschain/keeper/grpc_query.go index 8bfa3b2957..63a16d2e5e 100644 --- a/x/crosschain/keeper/grpc_query.go +++ b/x/crosschain/keeper/grpc_query.go @@ -9,10 +9,43 @@ import ( var _ types.QueryServer = Keeper{} -// Params returns params of the mint module. +// Params returns params of the cross chain module. func (k Keeper) Params(c context.Context, _ *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { ctx := sdk.UnwrapSDKContext(c) params := k.GetParams(ctx) return &types.QueryParamsResponse{Params: params}, nil } + +// CrossChainPackage returns the specified cross chain package +func (k Keeper) CrossChainPackage(c context.Context, req *types.QueryCrossChainPackageRequest) (*types.QueryCrossChainPackageResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + + pack, err := k.GetCrossChainPackage(ctx, sdk.ChannelID(req.ChannelId), req.Sequence) + if err != nil { + return nil, err + } + return &types.QueryCrossChainPackageResponse{ + Package: pack, + }, nil +} + +// SendSequence returns the send sequence of the channel +func (k Keeper) SendSequence(c context.Context, req *types.QuerySendSequenceRequest) (*types.QuerySendSequenceResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + sequence := k.GetSendSequence(ctx, sdk.ChannelID(req.ChannelId)) + + return &types.QuerySendSequenceResponse{ + Sequence: sequence, + }, nil +} + +// ReceiveSequence returns the receive sequence of the channel +func (k Keeper) ReceiveSequence(c context.Context, req *types.QueryReceiveSequenceRequest) (*types.QueryReceiveSequenceResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + sequence := k.GetReceiveSequence(ctx, sdk.ChannelID(req.ChannelId)) + + return &types.QueryReceiveSequenceResponse{ + Sequence: sequence, + }, nil +} diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 7aa463e53a..c01210e3f5 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -79,15 +79,15 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { } // CreateRawIBCPackageWithFee creates a cross chain package with given cross chain fee -func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, +func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, ) (uint64, error) { - if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, destChainID, channelID) != sdk.ChannelAllow { + if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, k.GetDestChainID(), channelID) != sdk.ChannelAllow { return 0, fmt.Errorf("channel %d is not allowed to write syn package", channelID) } - sequence := k.GetSendSequence(ctx, destChainID, channelID) - key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelID, sequence) + sequence := k.GetSendSequence(ctx, channelID) + key := types.BuildCrossChainPackageKey(k.GetSrcChainID(), k.GetDestChainID(), channelID, sequence) kvStore := ctx.KVStore(k.storeKey) if kvStore.Has(key) { return 0, fmt.Errorf("duplicated sequence") @@ -103,11 +103,11 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.Chai kvStore.Set(key, append(packageHeader, packageLoad...)) - k.IncrSendSequence(ctx, destChainID, channelID) + k.IncrSendSequence(ctx, channelID) err := ctx.EventManager().EmitTypedEvent(&types.EventCrossChain{ SrcChainId: uint32(k.GetSrcChainID()), - DestChainId: uint32(destChainID), + DestChainId: uint32(k.GetDestChainID()), ChannelId: uint32(channelID), Sequence: sequence, PackageType: uint32(packageType), @@ -182,31 +182,31 @@ func (k Keeper) GetDestChainID() sdk.ChainID { return k.cfg.destChainId } -// GetIBCPackage returns the ibc package by sequence -func (k Keeper) GetIBCPackage(ctx sdk.Context, destChainID sdk.ChainID, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { +// GetCrossChainPackage returns the ibc package by sequence +func (k Keeper) GetCrossChainPackage(ctx sdk.Context, channelId sdk.ChannelID, sequence uint64) ([]byte, error) { kvStore := ctx.KVStore(k.storeKey) - key := types.BuildIBCPackageKey(k.GetSrcChainID(), destChainID, channelId, sequence) + key := types.BuildCrossChainPackageKey(k.GetSrcChainID(), k.GetDestChainID(), channelId, sequence) return kvStore.Get(key), nil } // GetSendSequence returns the sending sequence of the channel -func (k Keeper) GetSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { - return k.getSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) +func (k Keeper) GetSendSequence(ctx sdk.Context, channelID sdk.ChannelID) uint64 { + return k.getSequence(ctx, k.GetDestChainID(), channelID, types.PrefixForSendSequenceKey) } // IncrSendSequence increases the sending sequence of the channel -func (k Keeper) IncrSendSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { - k.incrSequence(ctx, destChainID, channelID, types.PrefixForSendSequenceKey) +func (k Keeper) IncrSendSequence(ctx sdk.Context, channelID sdk.ChannelID) { + k.incrSequence(ctx, k.GetDestChainID(), channelID, types.PrefixForSendSequenceKey) } // GetReceiveSequence returns the receiving sequence of the channel -func (k Keeper) GetReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) uint64 { - return k.getSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) +func (k Keeper) GetReceiveSequence(ctx sdk.Context, channelID sdk.ChannelID) uint64 { + return k.getSequence(ctx, k.GetDestChainID(), channelID, types.PrefixForReceiveSequenceKey) } // IncrReceiveSequence increases the receiving sequence of the channel -func (k Keeper) IncrReceiveSequence(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID) { - k.incrSequence(ctx, destChainID, channelID, types.PrefixForReceiveSequenceKey) +func (k Keeper) IncrReceiveSequence(ctx sdk.Context, channelID sdk.ChannelID) { + k.incrSequence(ctx, k.GetDestChainID(), channelID, types.PrefixForReceiveSequenceKey) } // getSequence returns the sequence with a prefix diff --git a/x/crosschain/keeper/keeper_test.go b/x/crosschain/keeper/keeper_test.go index 90d41aa043..35c3111475 100644 --- a/x/crosschain/keeper/keeper_test.go +++ b/x/crosschain/keeper/keeper_test.go @@ -36,21 +36,21 @@ func TestTestSuite(t *testing.T) { } func (s *TestSuite) TestIncrSendSequence() { - beforeSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + beforeSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChannelID(1)) - s.app.CrossChainKeeper.IncrSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + s.app.CrossChainKeeper.IncrSendSequence(s.ctx, sdk.ChannelID(1)) - afterSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + afterSequence := s.app.CrossChainKeeper.GetSendSequence(s.ctx, sdk.ChannelID(1)) s.Require().EqualValues(afterSequence, beforeSequence+1) } func (s *TestSuite) TestIncrReceiveSequence() { - beforeSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + beforeSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChannelID(1)) - s.app.CrossChainKeeper.IncrReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + s.app.CrossChainKeeper.IncrReceiveSequence(s.ctx, sdk.ChannelID(1)) - afterSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChainID(1), sdk.ChannelID(1)) + afterSequence := s.app.CrossChainKeeper.GetReceiveSequence(s.ctx, sdk.ChannelID(1)) s.Require().EqualValues(afterSequence, beforeSequence+1) } diff --git a/x/crosschain/keeper/querier.go b/x/crosschain/keeper/querier.go deleted file mode 100644 index 5c081a3c6f..0000000000 --- a/x/crosschain/keeper/querier.go +++ /dev/null @@ -1,33 +0,0 @@ -package keeper - -import ( - abci "github.com/tendermint/tendermint/abci/types" - - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/crosschain/types" -) - -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case types.QueryParameters: - return queryParams(ctx, k, legacyQuerierCdc) - - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} - -func queryParams(ctx sdk.Context, k Keeper, legacyQuerierCdc *codec.LegacyAmino) ([]byte, error) { - params := k.GetParams(ctx) - - res, err := codec.MarshalJSONIndent(legacyQuerierCdc, params) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - - return res, nil -} diff --git a/x/crosschain/module.go b/x/crosschain/module.go index 05d244d00c..56a379da78 100644 --- a/x/crosschain/module.go +++ b/x/crosschain/module.go @@ -113,7 +113,7 @@ func (AppModule) QuerierRoute() string { return types.QuerierRoute } // LegacyQuerierHandler returns the x/params querier handler. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) + return nil } // RegisterServices registers a gRPC query service to respond to the diff --git a/x/crosschain/types/keys.go b/x/crosschain/types/keys.go index d84f7e7326..f4c8a83df6 100644 --- a/x/crosschain/types/keys.go +++ b/x/crosschain/types/keys.go @@ -37,7 +37,7 @@ var ( PrefixForChannelPermissionKey = []byte{0xc0} ) -func BuildIBCPackageKey(srcChainID, destChainID sdk.ChainID, channelID sdk.ChannelID, sequence uint64) []byte { +func BuildCrossChainPackageKey(srcChainID, destChainID sdk.ChainID, channelID sdk.ChannelID, sequence uint64) []byte { key := make([]byte, totalPackageKeyLength) copy(key[:prefixLength], PrefixForIbcPackageKey) diff --git a/x/crosschain/types/query.pb.go b/x/crosschain/types/query.pb.go index 0f216dc8e9..984242259e 100644 --- a/x/crosschain/types/query.pb.go +++ b/x/crosschain/types/query.pb.go @@ -112,33 +112,332 @@ func (m *QueryParamsResponse) GetParams() Params { return Params{} } +// QueryCrossChainPackageRequest is the request type for the Query/CrossChainPackage RPC method. +type QueryCrossChainPackageRequest struct { + ChannelId uint32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Sequence uint64 `protobuf:"varint,2,opt,name=sequence,proto3" json:"sequence,omitempty"` +} + +func (m *QueryCrossChainPackageRequest) Reset() { *m = QueryCrossChainPackageRequest{} } +func (m *QueryCrossChainPackageRequest) String() string { return proto.CompactTextString(m) } +func (*QueryCrossChainPackageRequest) ProtoMessage() {} +func (*QueryCrossChainPackageRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{2} +} +func (m *QueryCrossChainPackageRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCrossChainPackageRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCrossChainPackageRequest.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 *QueryCrossChainPackageRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCrossChainPackageRequest.Merge(m, src) +} +func (m *QueryCrossChainPackageRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryCrossChainPackageRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCrossChainPackageRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCrossChainPackageRequest proto.InternalMessageInfo + +func (m *QueryCrossChainPackageRequest) GetChannelId() uint32 { + if m != nil { + return m.ChannelId + } + return 0 +} + +func (m *QueryCrossChainPackageRequest) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + +// QueryCrossChainPackageResponse is the response type for the Query/CrossChainPackage RPC method. +type QueryCrossChainPackageResponse struct { + Package []byte `protobuf:"bytes,1,opt,name=package,proto3" json:"package,omitempty"` +} + +func (m *QueryCrossChainPackageResponse) Reset() { *m = QueryCrossChainPackageResponse{} } +func (m *QueryCrossChainPackageResponse) String() string { return proto.CompactTextString(m) } +func (*QueryCrossChainPackageResponse) ProtoMessage() {} +func (*QueryCrossChainPackageResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{3} +} +func (m *QueryCrossChainPackageResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCrossChainPackageResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCrossChainPackageResponse.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 *QueryCrossChainPackageResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCrossChainPackageResponse.Merge(m, src) +} +func (m *QueryCrossChainPackageResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryCrossChainPackageResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCrossChainPackageResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCrossChainPackageResponse proto.InternalMessageInfo + +func (m *QueryCrossChainPackageResponse) GetPackage() []byte { + if m != nil { + return m.Package + } + return nil +} + +// QuerySendSequenceRequest is the request type for the Query/SendSequence RPC method. +type QuerySendSequenceRequest struct { + ChannelId uint32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` +} + +func (m *QuerySendSequenceRequest) Reset() { *m = QuerySendSequenceRequest{} } +func (m *QuerySendSequenceRequest) String() string { return proto.CompactTextString(m) } +func (*QuerySendSequenceRequest) ProtoMessage() {} +func (*QuerySendSequenceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{4} +} +func (m *QuerySendSequenceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySendSequenceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySendSequenceRequest.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 *QuerySendSequenceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySendSequenceRequest.Merge(m, src) +} +func (m *QuerySendSequenceRequest) XXX_Size() int { + return m.Size() +} +func (m *QuerySendSequenceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySendSequenceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySendSequenceRequest proto.InternalMessageInfo + +func (m *QuerySendSequenceRequest) GetChannelId() uint32 { + if m != nil { + return m.ChannelId + } + return 0 +} + +// QuerySendSequenceResponse is the response type for the Query/SendSequence RPC method. +type QuerySendSequenceResponse struct { + Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` +} + +func (m *QuerySendSequenceResponse) Reset() { *m = QuerySendSequenceResponse{} } +func (m *QuerySendSequenceResponse) String() string { return proto.CompactTextString(m) } +func (*QuerySendSequenceResponse) ProtoMessage() {} +func (*QuerySendSequenceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{5} +} +func (m *QuerySendSequenceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySendSequenceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySendSequenceResponse.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 *QuerySendSequenceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySendSequenceResponse.Merge(m, src) +} +func (m *QuerySendSequenceResponse) XXX_Size() int { + return m.Size() +} +func (m *QuerySendSequenceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySendSequenceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySendSequenceResponse proto.InternalMessageInfo + +func (m *QuerySendSequenceResponse) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + +// QuerySendSequenceRequest is the request type for the Query/ReceiveSequence RPC method. +type QueryReceiveSequenceRequest struct { + ChannelId uint32 `protobuf:"varint,1,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` +} + +func (m *QueryReceiveSequenceRequest) Reset() { *m = QueryReceiveSequenceRequest{} } +func (m *QueryReceiveSequenceRequest) String() string { return proto.CompactTextString(m) } +func (*QueryReceiveSequenceRequest) ProtoMessage() {} +func (*QueryReceiveSequenceRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{6} +} +func (m *QueryReceiveSequenceRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryReceiveSequenceRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryReceiveSequenceRequest.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 *QueryReceiveSequenceRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryReceiveSequenceRequest.Merge(m, src) +} +func (m *QueryReceiveSequenceRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryReceiveSequenceRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryReceiveSequenceRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryReceiveSequenceRequest proto.InternalMessageInfo + +func (m *QueryReceiveSequenceRequest) GetChannelId() uint32 { + if m != nil { + return m.ChannelId + } + return 0 +} + +// QuerySendSequenceResponse is the response type for the Query/ReceiveSequence RPC method. +type QueryReceiveSequenceResponse struct { + Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` +} + +func (m *QueryReceiveSequenceResponse) Reset() { *m = QueryReceiveSequenceResponse{} } +func (m *QueryReceiveSequenceResponse) String() string { return proto.CompactTextString(m) } +func (*QueryReceiveSequenceResponse) ProtoMessage() {} +func (*QueryReceiveSequenceResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_3c0bc65cbea0cca3, []int{7} +} +func (m *QueryReceiveSequenceResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryReceiveSequenceResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryReceiveSequenceResponse.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 *QueryReceiveSequenceResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryReceiveSequenceResponse.Merge(m, src) +} +func (m *QueryReceiveSequenceResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryReceiveSequenceResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryReceiveSequenceResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryReceiveSequenceResponse proto.InternalMessageInfo + +func (m *QueryReceiveSequenceResponse) GetSequence() uint64 { + if m != nil { + return m.Sequence + } + return 0 +} + func init() { proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.crosschain.v1.QueryParamsRequest") proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.crosschain.v1.QueryParamsResponse") + proto.RegisterType((*QueryCrossChainPackageRequest)(nil), "cosmos.crosschain.v1.QueryCrossChainPackageRequest") + proto.RegisterType((*QueryCrossChainPackageResponse)(nil), "cosmos.crosschain.v1.QueryCrossChainPackageResponse") + proto.RegisterType((*QuerySendSequenceRequest)(nil), "cosmos.crosschain.v1.QuerySendSequenceRequest") + proto.RegisterType((*QuerySendSequenceResponse)(nil), "cosmos.crosschain.v1.QuerySendSequenceResponse") + proto.RegisterType((*QueryReceiveSequenceRequest)(nil), "cosmos.crosschain.v1.QueryReceiveSequenceRequest") + proto.RegisterType((*QueryReceiveSequenceResponse)(nil), "cosmos.crosschain.v1.QueryReceiveSequenceResponse") } func init() { proto.RegisterFile("cosmos/crosschain/v1/query.proto", fileDescriptor_3c0bc65cbea0cca3) } var fileDescriptor_3c0bc65cbea0cca3 = []byte{ - // 283 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x52, 0x48, 0xce, 0x2f, 0xce, - 0xcd, 0x2f, 0xd6, 0x4f, 0x2e, 0xca, 0x2f, 0x2e, 0x4e, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x2f, 0x33, - 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x81, 0xa8, - 0xd0, 0x43, 0xa8, 0xd0, 0x2b, 0x33, 0x94, 0x12, 0x49, 0xcf, 0x4f, 0xcf, 0x07, 0x2b, 0xd0, 0x07, - 0xb1, 0x20, 0x6a, 0xa5, 0x64, 0xd2, 0xf3, 0xf3, 0xd3, 0x73, 0x52, 0xf5, 0x13, 0x0b, 0x32, 0xf5, - 0x13, 0xf3, 0xf2, 0xf2, 0x4b, 0x12, 0x4b, 0x32, 0xf3, 0xf3, 0x8a, 0xa1, 0xb2, 0xaa, 0x58, 0xed, - 0x42, 0x32, 0x17, 0xac, 0x4c, 0x49, 0x84, 0x4b, 0x28, 0x10, 0x64, 0x7f, 0x40, 0x62, 0x51, 0x62, - 0x6e, 0x71, 0x50, 0x6a, 0x61, 0x69, 0x6a, 0x71, 0x89, 0x52, 0x20, 0x97, 0x30, 0x8a, 0x68, 0x71, - 0x41, 0x7e, 0x5e, 0x71, 0xaa, 0x90, 0x15, 0x17, 0x5b, 0x01, 0x58, 0x44, 0x82, 0x51, 0x81, 0x51, - 0x83, 0xdb, 0x48, 0x46, 0x0f, 0x9b, 0x73, 0xf5, 0x20, 0xba, 0x9c, 0x58, 0x4e, 0xdc, 0x93, 0x67, - 0x08, 0x82, 0xea, 0x30, 0xea, 0x65, 0xe4, 0x62, 0x05, 0x9b, 0x29, 0xd4, 0xcc, 0xc8, 0xc5, 0x06, - 0x51, 0x22, 0xa4, 0x81, 0xdd, 0x00, 0x4c, 0x17, 0x49, 0x69, 0x12, 0xa1, 0x12, 0xe2, 0x4a, 0x25, - 0x95, 0xa6, 0xcb, 0x4f, 0x26, 0x33, 0xc9, 0x09, 0xc9, 0xe8, 0x63, 0x0d, 0x02, 0x88, 0x7b, 0x9c, - 0x3c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, - 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3f, 0x3d, 0xb3, 0x24, - 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x17, 0x6e, 0x02, 0x98, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, - 0x40, 0x36, 0xae, 0xa4, 0xb2, 0x20, 0xb5, 0x38, 0x89, 0x0d, 0x1c, 0x94, 0xc6, 0x80, 0x00, 0x00, - 0x00, 0xff, 0xff, 0xe8, 0x38, 0x15, 0x95, 0xdf, 0x01, 0x00, 0x00, + // 514 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xb1, 0x6f, 0xd3, 0x40, + 0x14, 0xc6, 0x73, 0x55, 0x1b, 0xe0, 0x51, 0x84, 0x78, 0x64, 0x08, 0x26, 0x35, 0x91, 0xa1, 0x28, + 0x55, 0x85, 0x4f, 0x49, 0x91, 0x10, 0x11, 0x53, 0x3b, 0x75, 0x6b, 0xdd, 0xad, 0x4b, 0xe4, 0xda, + 0x27, 0xc7, 0x6a, 0x73, 0xe7, 0xfa, 0x9c, 0x88, 0xae, 0x30, 0xb2, 0x20, 0xb1, 0xf2, 0x07, 0xb0, + 0xf2, 0x5f, 0x74, 0xac, 0xc4, 0xc2, 0x84, 0x50, 0xc2, 0x1f, 0x82, 0x7c, 0xbe, 0x86, 0xd0, 0x5c, + 0xd2, 0x64, 0x4a, 0xee, 0xfc, 0x7d, 0xef, 0xfb, 0x49, 0xef, 0xb3, 0xa1, 0x1e, 0x08, 0xd9, 0x13, + 0x92, 0x06, 0xa9, 0x90, 0x32, 0xe8, 0xfa, 0x31, 0xa7, 0x83, 0x26, 0x3d, 0xef, 0xb3, 0xf4, 0xc2, + 0x4d, 0x52, 0x91, 0x09, 0xac, 0x14, 0x0a, 0xf7, 0x9f, 0xc2, 0x1d, 0x34, 0xad, 0x4a, 0x24, 0x22, + 0xa1, 0x04, 0x34, 0xff, 0x57, 0x68, 0xad, 0x5a, 0x24, 0x44, 0x74, 0xc6, 0xa8, 0x9f, 0xc4, 0xd4, + 0xe7, 0x5c, 0x64, 0x7e, 0x16, 0x0b, 0x2e, 0xf5, 0xd3, 0x4d, 0x63, 0xd6, 0xc4, 0x5c, 0x25, 0x73, + 0x2a, 0x80, 0x87, 0x79, 0xfe, 0x81, 0x9f, 0xfa, 0x3d, 0xe9, 0xb1, 0xf3, 0x3e, 0x93, 0x99, 0x73, + 0x08, 0x8f, 0xff, 0xbb, 0x95, 0x89, 0xe0, 0x92, 0x61, 0x1b, 0xca, 0x89, 0xba, 0xa9, 0x92, 0x3a, + 0x69, 0xdc, 0x6f, 0xd5, 0x5c, 0x13, 0xae, 0x5b, 0xb8, 0x76, 0x57, 0x2f, 0x7f, 0x3d, 0x2b, 0x79, + 0xda, 0xe1, 0x1c, 0xc3, 0x86, 0x1a, 0xb9, 0x97, 0x4b, 0xf7, 0x72, 0xe9, 0x81, 0x1f, 0x9c, 0xfa, + 0x11, 0xd3, 0x99, 0xb8, 0x01, 0x10, 0x74, 0x7d, 0xce, 0xd9, 0x59, 0x27, 0x0e, 0x55, 0xc0, 0x03, + 0xef, 0x9e, 0xbe, 0xd9, 0x0f, 0xd1, 0x82, 0xbb, 0x32, 0x57, 0xf2, 0x80, 0x55, 0x57, 0xea, 0xa4, + 0xb1, 0xea, 0x8d, 0xcf, 0x4e, 0x1b, 0xec, 0x59, 0xb3, 0x35, 0x79, 0x15, 0xee, 0x24, 0xc5, 0x95, + 0x9a, 0xbc, 0xee, 0x5d, 0x1f, 0x9d, 0xb7, 0x50, 0x55, 0xde, 0x23, 0xc6, 0xc3, 0x23, 0x3d, 0x70, + 0x31, 0x24, 0xe7, 0x0d, 0x3c, 0x31, 0x58, 0x75, 0xe2, 0x24, 0x2f, 0xb9, 0xc1, 0xfb, 0x0e, 0x9e, + 0x2a, 0xa3, 0xc7, 0x02, 0x16, 0x0f, 0xd8, 0x92, 0xb1, 0x6d, 0xa8, 0x99, 0xdd, 0xb7, 0x27, 0xb7, + 0x3e, 0xad, 0xc1, 0x9a, 0x32, 0xe3, 0x47, 0x02, 0xe5, 0x62, 0x51, 0xd8, 0x30, 0xaf, 0x71, 0xba, + 0x17, 0xd6, 0xd6, 0x02, 0xca, 0x82, 0xc2, 0x79, 0xf1, 0xe1, 0xc7, 0x9f, 0x2f, 0x2b, 0x36, 0xd6, + 0xa8, 0xb1, 0x88, 0x45, 0x2b, 0xf0, 0x3b, 0x81, 0x47, 0x53, 0x5b, 0xc3, 0x9d, 0x39, 0x31, 0xb3, + 0xfa, 0x63, 0xbd, 0x5e, 0xce, 0xa4, 0x31, 0x9b, 0x0a, 0x73, 0x1b, 0xb7, 0xe8, 0xec, 0xf7, 0xa5, + 0xa3, 0x8e, 0x1d, 0xdd, 0x18, 0xfc, 0x4a, 0x60, 0x7d, 0x72, 0xe5, 0xe8, 0xce, 0x49, 0x36, 0xd4, + 0xca, 0xa2, 0x0b, 0xeb, 0x35, 0xe4, 0xb6, 0x82, 0xdc, 0xc4, 0xe7, 0x66, 0x48, 0xc9, 0x78, 0xd8, + 0xb9, 0x5e, 0x31, 0x7e, 0x23, 0xf0, 0xf0, 0x46, 0x35, 0xb0, 0x39, 0x27, 0xd1, 0x5c, 0x42, 0xab, + 0xb5, 0x8c, 0x45, 0x73, 0xba, 0x8a, 0xb3, 0x81, 0x2f, 0xcd, 0x9c, 0x69, 0x61, 0x1b, 0xa3, 0xee, + 0xee, 0x5f, 0x0e, 0x6d, 0x72, 0x35, 0xb4, 0xc9, 0xef, 0xa1, 0x4d, 0x3e, 0x8f, 0xec, 0xd2, 0xd5, + 0xc8, 0x2e, 0xfd, 0x1c, 0xd9, 0xa5, 0x63, 0x1a, 0xc5, 0x59, 0xb7, 0x7f, 0xe2, 0x06, 0xa2, 0x37, + 0x9e, 0xa5, 0x7e, 0x5e, 0xc9, 0xf0, 0x94, 0xbe, 0x9f, 0x1c, 0x9c, 0x5d, 0x24, 0x4c, 0x9e, 0x94, + 0xd5, 0xe7, 0x6c, 0xe7, 0x6f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x45, 0x6c, 0xf9, 0x89, 0x63, 0x05, + 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -153,8 +452,14 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { - // Params returns the total set of minting parameters. + // Params returns the total set of cross chain parameters. Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) + // CrossChainPackage returns the specified cross chain package + CrossChainPackage(ctx context.Context, in *QueryCrossChainPackageRequest, opts ...grpc.CallOption) (*QueryCrossChainPackageResponse, error) + // SendSequence returns the send sequence of the channel + SendSequence(ctx context.Context, in *QuerySendSequenceRequest, opts ...grpc.CallOption) (*QuerySendSequenceResponse, error) + // ReceiveSequence returns the receive sequence of the channel + ReceiveSequence(ctx context.Context, in *QueryReceiveSequenceRequest, opts ...grpc.CallOption) (*QueryReceiveSequenceResponse, error) } type queryClient struct { @@ -174,10 +479,43 @@ func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts . return out, nil } +func (c *queryClient) CrossChainPackage(ctx context.Context, in *QueryCrossChainPackageRequest, opts ...grpc.CallOption) (*QueryCrossChainPackageResponse, error) { + out := new(QueryCrossChainPackageResponse) + err := c.cc.Invoke(ctx, "/cosmos.crosschain.v1.Query/CrossChainPackage", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) SendSequence(ctx context.Context, in *QuerySendSequenceRequest, opts ...grpc.CallOption) (*QuerySendSequenceResponse, error) { + out := new(QuerySendSequenceResponse) + err := c.cc.Invoke(ctx, "/cosmos.crosschain.v1.Query/SendSequence", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ReceiveSequence(ctx context.Context, in *QueryReceiveSequenceRequest, opts ...grpc.CallOption) (*QueryReceiveSequenceResponse, error) { + out := new(QueryReceiveSequenceResponse) + err := c.cc.Invoke(ctx, "/cosmos.crosschain.v1.Query/ReceiveSequence", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { - // Params returns the total set of minting parameters. + // Params returns the total set of cross chain parameters. Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) + // CrossChainPackage returns the specified cross chain package + CrossChainPackage(context.Context, *QueryCrossChainPackageRequest) (*QueryCrossChainPackageResponse, error) + // SendSequence returns the send sequence of the channel + SendSequence(context.Context, *QuerySendSequenceRequest) (*QuerySendSequenceResponse, error) + // ReceiveSequence returns the receive sequence of the channel + ReceiveSequence(context.Context, *QueryReceiveSequenceRequest) (*QueryReceiveSequenceResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. @@ -187,6 +525,15 @@ type UnimplementedQueryServer struct { func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") } +func (*UnimplementedQueryServer) CrossChainPackage(ctx context.Context, req *QueryCrossChainPackageRequest) (*QueryCrossChainPackageResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method CrossChainPackage not implemented") +} +func (*UnimplementedQueryServer) SendSequence(ctx context.Context, req *QuerySendSequenceRequest) (*QuerySendSequenceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SendSequence not implemented") +} +func (*UnimplementedQueryServer) ReceiveSequence(ctx context.Context, req *QueryReceiveSequenceRequest) (*QueryReceiveSequenceResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReceiveSequence not implemented") +} func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) @@ -210,6 +557,60 @@ func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interf return interceptor(ctx, in, info, handler) } +func _Query_CrossChainPackage_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryCrossChainPackageRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).CrossChainPackage(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.crosschain.v1.Query/CrossChainPackage", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).CrossChainPackage(ctx, req.(*QueryCrossChainPackageRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_SendSequence_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QuerySendSequenceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).SendSequence(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.crosschain.v1.Query/SendSequence", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).SendSequence(ctx, req.(*QuerySendSequenceRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ReceiveSequence_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryReceiveSequenceRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ReceiveSequence(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.crosschain.v1.Query/ReceiveSequence", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ReceiveSequence(ctx, req.(*QueryReceiveSequenceRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "cosmos.crosschain.v1.Query", HandlerType: (*QueryServer)(nil), @@ -218,6 +619,18 @@ var _Query_serviceDesc = grpc.ServiceDesc{ MethodName: "Params", Handler: _Query_Params_Handler, }, + { + MethodName: "CrossChainPackage", + Handler: _Query_CrossChainPackage_Handler, + }, + { + MethodName: "SendSequence", + Handler: _Query_SendSequence_Handler, + }, + { + MethodName: "ReceiveSequence", + Handler: _Query_ReceiveSequence_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "cosmos/crosschain/v1/query.proto", @@ -279,36 +692,287 @@ func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { - offset -= sovQuery(v) - base := offset - for v >= 1<<7 { - dAtA[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ +func (m *QueryCrossChainPackageRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err } - dAtA[offset] = uint8(v) - return base + return dAtA[:n], nil } -func (m *QueryParamsRequest) Size() (n int) { - if m == nil { - return 0 - } - var l int - _ = l - return n + +func (m *QueryCrossChainPackageRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *QueryParamsResponse) Size() (n int) { - if m == nil { - return 0 - } +func (m *QueryCrossChainPackageRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i var l int _ = l - l = m.Params.Size() - n += 1 + l + sovQuery(uint64(l)) - return n -} + if m.Sequence != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) + i-- + dAtA[i] = 0x10 + } + if m.ChannelId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ChannelId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryCrossChainPackageResponse) 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 *QueryCrossChainPackageResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCrossChainPackageResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Package) > 0 { + i -= len(m.Package) + copy(dAtA[i:], m.Package) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Package))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QuerySendSequenceRequest) 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 *QuerySendSequenceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySendSequenceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ChannelId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ChannelId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QuerySendSequenceResponse) 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 *QuerySendSequenceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySendSequenceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sequence != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryReceiveSequenceRequest) 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 *QueryReceiveSequenceRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryReceiveSequenceRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ChannelId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.ChannelId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryReceiveSequenceResponse) 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 *QueryReceiveSequenceResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryReceiveSequenceResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Sequence != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.Sequence)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func (m *QueryCrossChainPackageRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChannelId != 0 { + n += 1 + sovQuery(uint64(m.ChannelId)) + } + if m.Sequence != 0 { + n += 1 + sovQuery(uint64(m.Sequence)) + } + return n +} + +func (m *QueryCrossChainPackageResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Package) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QuerySendSequenceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChannelId != 0 { + n += 1 + sovQuery(uint64(m.ChannelId)) + } + return n +} + +func (m *QuerySendSequenceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sequence != 0 { + n += 1 + sovQuery(uint64(m.Sequence)) + } + return n +} + +func (m *QueryReceiveSequenceRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.ChannelId != 0 { + n += 1 + sovQuery(uint64(m.ChannelId)) + } + return n +} + +func (m *QueryReceiveSequenceResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Sequence != 0 { + n += 1 + sovQuery(uint64(m.Sequence)) + } + return n +} func sovQuery(x uint64) (n int) { return (math_bits.Len64(x|1) + 6) / 7 @@ -449,6 +1113,454 @@ func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { } return nil } +func (m *QueryCrossChainPackageRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryCrossChainPackageRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCrossChainPackageRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) + } + m.ChannelId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryCrossChainPackageResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryCrossChainPackageResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCrossChainPackageResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Package", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Package = append(m.Package[:0], dAtA[iNdEx:postIndex]...) + if m.Package == nil { + m.Package = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySendSequenceRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySendSequenceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySendSequenceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) + } + m.ChannelId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySendSequenceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySendSequenceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySendSequenceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryReceiveSequenceRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryReceiveSequenceRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryReceiveSequenceRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field ChannelId", wireType) + } + m.ChannelId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.ChannelId |= uint32(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryReceiveSequenceResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryReceiveSequenceResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryReceiveSequenceResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) + } + m.Sequence = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Sequence |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func skipQuery(dAtA []byte) (n int, err error) { l := len(dAtA) iNdEx := 0 diff --git a/x/crosschain/types/query.pb.gw.go b/x/crosschain/types/query.pb.gw.go index 331a372259..0260f94e5a 100644 --- a/x/crosschain/types/query.pb.gw.go +++ b/x/crosschain/types/query.pb.gw.go @@ -51,6 +51,114 @@ func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshal } +var ( + filter_Query_CrossChainPackage_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_CrossChainPackage_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCrossChainPackageRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_CrossChainPackage_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.CrossChainPackage(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_CrossChainPackage_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCrossChainPackageRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_CrossChainPackage_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.CrossChainPackage(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_SendSequence_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_SendSequence_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySendSequenceRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SendSequence_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.SendSequence(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_SendSequence_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySendSequenceRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_SendSequence_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.SendSequence(ctx, &protoReq) + return msg, metadata, err + +} + +var ( + filter_Query_ReceiveSequence_0 = &utilities.DoubleArray{Encoding: map[string]int{}, Base: []int(nil), Check: []int(nil)} +) + +func request_Query_ReceiveSequence_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryReceiveSequenceRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ReceiveSequence_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := client.ReceiveSequence(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ReceiveSequence_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryReceiveSequenceRequest + var metadata runtime.ServerMetadata + + if err := req.ParseForm(); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_Query_ReceiveSequence_0); err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err) + } + + msg, err := server.ReceiveSequence(ctx, &protoReq) + return msg, metadata, err + +} + // RegisterQueryHandlerServer registers the http handlers for service Query to "mux". // UnaryRPC :call QueryServer directly. // StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. @@ -80,6 +188,75 @@ func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, serv }) + mux.Handle("GET", pattern_Query_CrossChainPackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_CrossChainPackage_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_CrossChainPackage_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SendSequence_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_SendSequence_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SendSequence_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ReceiveSequence_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ReceiveSequence_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ReceiveSequence_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } @@ -141,13 +318,85 @@ func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, clie }) + mux.Handle("GET", pattern_Query_CrossChainPackage_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_CrossChainPackage_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_CrossChainPackage_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SendSequence_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_SendSequence_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SendSequence_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ReceiveSequence_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ReceiveSequence_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ReceiveSequence_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + return nil } var ( pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "crosschain", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_CrossChainPackage_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "crosschain", "v1", "cross_chain_package"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_SendSequence_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "crosschain", "v1", "send_sequence"}, "", runtime.AssumeColonVerbOpt(false))) + + pattern_Query_ReceiveSequence_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "crosschain", "v1", "receive_sequence"}, "", runtime.AssumeColonVerbOpt(false))) ) var ( forward_Query_Params_0 = runtime.ForwardResponseMessage + + forward_Query_CrossChainPackage_0 = runtime.ForwardResponseMessage + + forward_Query_SendSequence_0 = runtime.ForwardResponseMessage + + forward_Query_ReceiveSequence_0 = runtime.ForwardResponseMessage ) diff --git a/x/oracle/keeper/grpc_query.go b/x/oracle/keeper/grpc_query.go new file mode 100644 index 0000000000..aa2280b2a9 --- /dev/null +++ b/x/oracle/keeper/grpc_query.go @@ -0,0 +1,7 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/x/oracle/types" +) + +var _ types.QueryServer = Keeper{} diff --git a/x/oracle/keeper/grpc_query_params.go b/x/oracle/keeper/grpc_query_params.go new file mode 100644 index 0000000000..ec7d9686c4 --- /dev/null +++ b/x/oracle/keeper/grpc_query_params.go @@ -0,0 +1,20 @@ +package keeper + +import ( + "context" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/oracle/types" +) + +func (k Keeper) Params(c context.Context, req *types.QueryParamsRequest) (*types.QueryParamsResponse, error) { + if req == nil { + return nil, status.Error(codes.InvalidArgument, "invalid request") + } + ctx := sdk.UnwrapSDKContext(c) + + return &types.QueryParamsResponse{Params: k.GetParams(ctx)}, nil +} diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index ef85bcd85c..17e74553fa 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -173,3 +173,9 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) ([]string, er return signedRelayers, nil } + +// GetParams returns the current params +func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { + k.paramSpace.GetParamSet(ctx, ¶ms) + return params +} diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index cec85a5031..29f2ee76bf 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -45,7 +45,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg return nil, sdkerrors.Wrapf(types.ErrInvalidSrcChainId, fmt.Sprintf("src chain id(%d) is not supported", req.SrcChainId)) } - sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), types.RelayPackagesChannelId) + sequence := k.oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, types.RelayPackagesChannelId) if sequence != req.Sequence { return nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", types.RelayPackagesChannelId, sequence)) } @@ -66,7 +66,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg for idx := range packages { pack := packages[idx] - relayerFee, event, err := handlePackage(ctx, req, k.oracleKeeper, sdk.ChainID(req.SrcChainId), &pack) + relayerFee, event, err := handlePackage(ctx, req, k.oracleKeeper, &pack) if err != nil { // only do log, but let rest package get chance to execute. logger.Error("process package failed", "channel", pack.ChannelId, "sequence", pack.Sequence, "error", err.Error()) @@ -79,7 +79,7 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg totalRelayerFee = totalRelayerFee.Add(totalRelayerFee, relayerFee) // increase channel sequence - k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, sdk.ChainID(req.SrcChainId), pack.ChannelId) + k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, pack.ChannelId) } err = distributeReward(ctx, k.oracleKeeper, req.FromAddress, signedRelayers, totalRelayerFee) @@ -140,7 +140,12 @@ func distributeReward(ctx sdk.Context, oracleKeeper Keeper, relayer string, sign return err } -func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, chainId sdk.ChainID, pack *types.Package) (*big.Int, *types.EventPackageClaim, error) { +func handlePackage( + ctx sdk.Context, + req *types.MsgClaim, + oracleKeeper Keeper, + pack *types.Package, +) (*big.Int, *types.EventPackageClaim, error) { logger := oracleKeeper.Logger(ctx) crossChainApp := oracleKeeper.CrossChainKeeper.GetCrossChainApp(pack.ChannelId) @@ -148,9 +153,10 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch return nil, nil, sdkerrors.Wrapf(types.ErrChannelNotRegistered, "channel %d not registered", pack.ChannelId) } - sequence := oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, chainId, pack.ChannelId) + sequence := oracleKeeper.CrossChainKeeper.GetReceiveSequence(ctx, pack.ChannelId) if sequence != pack.Sequence { - return nil, nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidReceiveSequence, + fmt.Sprintf("current sequence of channel %d is %d", pack.ChannelId, sequence)) } packageHeader, err := sdk.DecodePackageHeader(pack.Payload) @@ -159,11 +165,13 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch } if packageHeader.Timestamp != req.Timestamp { - return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, packageHeader.Timestamp) + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPayloadHeader, + "timestamp(%d) is not the same in payload header(%d)", req.Timestamp, packageHeader.Timestamp) } if !sdk.IsValidCrossChainPackageType(packageHeader.PackageType) { - return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, fmt.Sprintf("package type %d is invalid", packageHeader.PackageType)) + return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPackageType, + fmt.Sprintf("package type %d is invalid", packageHeader.PackageType)) } cacheCtx, write := ctx.CacheContext() @@ -179,10 +187,11 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch var ibcErr error var sendSeq uint64 if len(pack.Payload) >= sdk.SynPackageHeaderLength { - sendSeq, ibcErr = oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, chainId, - pack.ChannelId, sdk.FailAckCrossChainPackageType, pack.Payload[sdk.SynPackageHeaderLength:], packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) + sendSeq, ibcErr = oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, pack.ChannelId, + sdk.FailAckCrossChainPackageType, pack.Payload[sdk.SynPackageHeaderLength:], packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) } else { - logger.Error("found payload without header", "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) + logger.Error("found payload without header", + "channelID", pack.ChannelId, "sequence", pack.Sequence, "payload", hex.EncodeToString(pack.Payload)) return nil, nil, sdkerrors.Wrapf(types.ErrInvalidPackage, "payload without header") } @@ -192,8 +201,8 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch } sendSequence = int64(sendSeq) } else if len(result.Payload) != 0 { - sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, chainId, - pack.ChannelId, sdk.AckCrossChainPackageType, result.Payload, packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) + sendSeq, err := oracleKeeper.CrossChainKeeper.CreateRawIBCPackageWithFee(ctx, pack.ChannelId, + sdk.AckCrossChainPackageType, result.Payload, packageHeader.AckRelayerFee, sdk.NilAckRelayerFee) if err != nil { logger.Error("failed to write AckCrossChainPackage", "err", err) return nil, nil, err @@ -218,7 +227,13 @@ func handlePackage(ctx sdk.Context, req *types.MsgClaim, oracleKeeper Keeper, ch return packageHeader.SynRelayerFee, claimEvent, nil } -func executeClaim(ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, packageType sdk.CrossChainPackageType, relayerFee *big.Int) (crash bool, result sdk.ExecuteResult) { +func executeClaim( + ctx sdk.Context, + app sdk.CrossChainApplication, + payload []byte, + packageType sdk.CrossChainPackageType, + relayerFee *big.Int, +) (crash bool, result sdk.ExecuteResult) { defer func() { if r := recover(); r != nil { log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack())) diff --git a/x/oracle/keeper/querier.go b/x/oracle/keeper/querier.go deleted file mode 100644 index 9c80a39b3d..0000000000 --- a/x/oracle/keeper/querier.go +++ /dev/null @@ -1,17 +0,0 @@ -package keeper - -import ( - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - abci "github.com/tendermint/tendermint/abci/types" -) - -func NewQuerier(k Keeper, legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - default: - return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unknown query path: %s", path[0]) - } - } -} diff --git a/x/oracle/module.go b/x/oracle/module.go index c6f206c541..c62cdffda2 100644 --- a/x/oracle/module.go +++ b/x/oracle/module.go @@ -109,7 +109,7 @@ func (AppModule) QuerierRoute() string { return types.QuerierRoute } // LegacyQuerierHandler returns the x/params querier handler. func (am AppModule) LegacyQuerierHandler(legacyQuerierCdc *codec.LegacyAmino) sdk.Querier { - return keeper.NewQuerier(am.keeper, legacyQuerierCdc) + return nil } // RegisterServices registers a gRPC query service to respond to the diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index c6b339dac8..0830b51582 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -14,14 +14,14 @@ type StakingKeeper interface { } type CrossChainKeeper interface { - CreateRawIBCPackageWithFee(ctx sdk.Context, destChainID sdk.ChainID, channelID sdk.ChannelID, + CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.ChannelID, packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, ) (uint64, error) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication GetSrcChainID() sdk.ChainID IsDestChainSupported(chainID sdk.ChainID) bool - GetReceiveSequence(ctx sdk.Context, srcChainID sdk.ChainID, channelID sdk.ChannelID) uint64 - IncrReceiveSequence(ctx sdk.Context, srcChainID sdk.ChainID, channelID sdk.ChannelID) + GetReceiveSequence(ctx sdk.Context, channelID sdk.ChannelID) uint64 + IncrReceiveSequence(ctx sdk.Context, channelID sdk.ChannelID) } type BankKeeper interface { diff --git a/x/oracle/types/query.pb.go b/x/oracle/types/query.pb.go index 14161570d5..d5c13cdf13 100644 --- a/x/oracle/types/query.pb.go +++ b/x/oracle/types/query.pb.go @@ -6,10 +6,16 @@ package types import ( context "context" fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" grpc1 "github.com/gogo/protobuf/grpc" proto "github.com/gogo/protobuf/proto" + _ "google.golang.org/genproto/googleapis/api/annotations" grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" math "math" + math_bits "math/bits" ) // Reference imports to suppress errors if they are not otherwise used. @@ -23,19 +29,116 @@ var _ = math.Inf // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package +// QueryParamsRequest is the request type for the Query/Params RPC method. +type QueryParamsRequest struct { +} + +func (m *QueryParamsRequest) Reset() { *m = QueryParamsRequest{} } +func (m *QueryParamsRequest) String() string { return proto.CompactTextString(m) } +func (*QueryParamsRequest) ProtoMessage() {} +func (*QueryParamsRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_9f804c4644f3aaef, []int{0} +} +func (m *QueryParamsRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsRequest.Merge(m, src) +} +func (m *QueryParamsRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsRequest proto.InternalMessageInfo + +// QueryParamsResponse is the response type for the Query/Params RPC method. +type QueryParamsResponse struct { + // params defines the parameters of the module. + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` +} + +func (m *QueryParamsResponse) Reset() { *m = QueryParamsResponse{} } +func (m *QueryParamsResponse) String() string { return proto.CompactTextString(m) } +func (*QueryParamsResponse) ProtoMessage() {} +func (*QueryParamsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_9f804c4644f3aaef, []int{1} +} +func (m *QueryParamsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryParamsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryParamsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryParamsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryParamsResponse.Merge(m, src) +} +func (m *QueryParamsResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryParamsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryParamsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryParamsResponse proto.InternalMessageInfo + +func (m *QueryParamsResponse) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func init() { + proto.RegisterType((*QueryParamsRequest)(nil), "cosmos.oracle.v1.QueryParamsRequest") + proto.RegisterType((*QueryParamsResponse)(nil), "cosmos.oracle.v1.QueryParamsResponse") +} + func init() { proto.RegisterFile("cosmos/oracle/v1/query.proto", fileDescriptor_9f804c4644f3aaef) } var fileDescriptor_9f804c4644f3aaef = []byte{ - // 133 bytes of a gzipped FileDescriptorProto + // 276 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x49, 0xce, 0x2f, 0xce, 0xcd, 0x2f, 0xd6, 0xcf, 0x2f, 0x4a, 0x4c, 0xce, 0x49, 0xd5, 0x2f, 0x33, 0xd4, 0x2f, 0x2c, 0x4d, 0x2d, 0xaa, 0xd4, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x12, 0x80, 0xc8, 0xea, 0x41, 0x64, 0xf5, - 0xca, 0x0c, 0x8d, 0xd8, 0xb9, 0x58, 0x03, 0x41, 0x0a, 0x9c, 0x5c, 0x4f, 0x3c, 0x92, 0x63, 0xbc, - 0xf0, 0x48, 0x8e, 0xf1, 0xc1, 0x23, 0x39, 0xc6, 0x09, 0x8f, 0xe5, 0x18, 0x2e, 0x3c, 0x96, 0x63, - 0xb8, 0xf1, 0x58, 0x8e, 0x21, 0x4a, 0x3b, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, - 0x57, 0x1f, 0x6a, 0x3a, 0x84, 0xd2, 0x2d, 0x4e, 0xc9, 0xd6, 0xaf, 0x80, 0x59, 0x55, 0x52, 0x59, - 0x90, 0x5a, 0x9c, 0xc4, 0x06, 0xb6, 0xc8, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xfc, 0xc4, 0x7d, - 0x86, 0x88, 0x00, 0x00, 0x00, + 0xca, 0x0c, 0xa5, 0x44, 0xd2, 0xf3, 0xd3, 0xf3, 0xc1, 0x92, 0xfa, 0x20, 0x16, 0x44, 0x9d, 0x94, + 0x4c, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0xaa, 0x7e, 0x62, 0x41, 0xa6, 0x7e, 0x62, 0x5e, 0x5e, 0x7e, + 0x49, 0x62, 0x49, 0x66, 0x7e, 0x5e, 0x31, 0x54, 0x56, 0x16, 0xc3, 0x0e, 0xa8, 0x79, 0x60, 0x69, + 0x25, 0x11, 0x2e, 0xa1, 0x40, 0x90, 0x9d, 0x01, 0x89, 0x45, 0x89, 0xb9, 0xc5, 0x41, 0xa9, 0x85, + 0xa5, 0xa9, 0xc5, 0x25, 0x4a, 0xbe, 0x5c, 0xc2, 0x28, 0xa2, 0xc5, 0x05, 0xf9, 0x79, 0xc5, 0xa9, + 0x42, 0x66, 0x5c, 0x6c, 0x05, 0x60, 0x11, 0x09, 0x46, 0x05, 0x46, 0x0d, 0x6e, 0x23, 0x09, 0x3d, + 0x74, 0x27, 0xea, 0x41, 0x74, 0x38, 0xb1, 0x9c, 0xb8, 0x27, 0xcf, 0x10, 0x04, 0x55, 0x6d, 0xd4, + 0xc0, 0xc8, 0xc5, 0x0a, 0x36, 0x4f, 0xa8, 0x9c, 0x8b, 0x0d, 0xa2, 0x42, 0x48, 0x05, 0x53, 0x2f, + 0xa6, 0x43, 0xa4, 0x54, 0x09, 0xa8, 0x82, 0x38, 0x4c, 0x49, 0xa1, 0xe9, 0xf2, 0x93, 0xc9, 0x4c, + 0x52, 0x42, 0x12, 0xfa, 0x18, 0xbe, 0x85, 0x38, 0xc1, 0xc9, 0xf5, 0xc4, 0x23, 0x39, 0xc6, 0x0b, + 0x8f, 0xe4, 0x18, 0x1f, 0x3c, 0x92, 0x63, 0x9c, 0xf0, 0x58, 0x8e, 0xe1, 0xc2, 0x63, 0x39, 0x86, + 0x1b, 0x8f, 0xe5, 0x18, 0xa2, 0xb4, 0xd3, 0x33, 0x4b, 0x32, 0x4a, 0x93, 0xf4, 0x92, 0xf3, 0x73, + 0x61, 0xba, 0x21, 0x94, 0x6e, 0x71, 0x4a, 0xb6, 0x7e, 0x05, 0xcc, 0xa8, 0x92, 0xca, 0x82, 0xd4, + 0xe2, 0x24, 0x36, 0x70, 0xa8, 0x19, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xb9, 0x3b, 0xd3, 0x95, + 0xba, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -50,6 +153,8 @@ const _ = grpc.SupportPackageIsVersion4 // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type QueryClient interface { + // Params returns the total set of cross chain parameters. + Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) } type queryClient struct { @@ -60,22 +165,371 @@ func NewQueryClient(cc grpc1.ClientConn) QueryClient { return &queryClient{cc} } +func (c *queryClient) Params(ctx context.Context, in *QueryParamsRequest, opts ...grpc.CallOption) (*QueryParamsResponse, error) { + out := new(QueryParamsResponse) + err := c.cc.Invoke(ctx, "/cosmos.oracle.v1.Query/Params", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // QueryServer is the server API for Query service. type QueryServer interface { + // Params returns the total set of cross chain parameters. + Params(context.Context, *QueryParamsRequest) (*QueryParamsResponse, error) } // UnimplementedQueryServer can be embedded to have forward compatible implementations. type UnimplementedQueryServer struct { } +func (*UnimplementedQueryServer) Params(ctx context.Context, req *QueryParamsRequest) (*QueryParamsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Params not implemented") +} + func RegisterQueryServer(s grpc1.Server, srv QueryServer) { s.RegisterService(&_Query_serviceDesc, srv) } +func _Query_Params_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryParamsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Params(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/cosmos.oracle.v1.Query/Params", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Params(ctx, req.(*QueryParamsRequest)) + } + return interceptor(ctx, in, info, handler) +} + var _Query_serviceDesc = grpc.ServiceDesc{ ServiceName: "cosmos.oracle.v1.Query", HandlerType: (*QueryServer)(nil), - Methods: []grpc.MethodDesc{}, - Streams: []grpc.StreamDesc{}, - Metadata: "cosmos/oracle/v1/query.proto", + Methods: []grpc.MethodDesc{ + { + MethodName: "Params", + Handler: _Query_Params_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "cosmos/oracle/v1/query.proto", +} + +func (m *QueryParamsRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + +func (m *QueryParamsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryParamsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryParamsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryParamsRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + +func (m *QueryParamsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovQuery(uint64(l)) + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) } +func (m *QueryParamsRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryParamsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryParamsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryParamsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/oracle/types/query.pb.gw.go b/x/oracle/types/query.pb.gw.go new file mode 100644 index 0000000000..9618c73c03 --- /dev/null +++ b/x/oracle/types/query.pb.gw.go @@ -0,0 +1,153 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: cosmos/oracle/v1/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := client.Params(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Params_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryParamsRequest + var metadata runtime.ServerMetadata + + msg, err := server.Params(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Params_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_Params_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Params_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Params_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_Params_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"cosmos", "oracle", "v1", "params"}, "", runtime.AssumeColonVerbOpt(false))) +) + +var ( + forward_Query_Params_0 = runtime.ForwardResponseMessage +) From 94c002b0a4b29282148be1216b349c4fab9b5504 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 11 Jan 2023 15:54:51 +0800 Subject: [PATCH 40/50] update the logic checking inturn relayers --- x/oracle/keeper/keeper.go | 16 ++++++++-------- x/oracle/keeper/keeper_test.go | 14 ++++---------- 2 files changed, 12 insertions(+), 18 deletions(-) diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 17e74553fa..671553a5ad 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -106,17 +106,17 @@ func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Valid curTime := ctx.BlockTime().Unix() relayerTimeout, relayerBackoffTime := k.GetRelayerParam(ctx) - // check block time with package timestamp + // inturn validator can always relay pacakge + if uint64(validatorIndex) == inturnValidatorIndex { + return true, nil + } + + // not inturn validators can not relay in the timeout duration if uint64(curTime)-claim.Timestamp <= relayerTimeout { - if uint64(validatorIndex) == inturnValidatorIndex { - return true, nil - } return false, nil } - - backoffIndex := (uint64(curTime)-claim.Timestamp-relayerTimeout-1)/relayerBackoffTime + 1 - - return uint64(validatorIndex) == (inturnValidatorIndex+backoffIndex)%uint64(len(validators)), nil + validatorDistance := (validatorIndex - int64(inturnValidatorIndex) + int64(len(validators))) % int64(len(validators)) + return curTime > int64(claim.Timestamp+relayerTimeout)+(validatorDistance-1)*int64(relayerBackoffTime), nil } // CheckClaim checks the bls signature diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 3f64cbc143..6623c9a9df 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -111,12 +111,6 @@ func (s *TestSuite) TestProcessClaim() { _, err := s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) s.Require().Nil(err, "error should be nil") - // not in turn - s.ctx = s.ctx.WithBlockTime(time.Unix(int64(msgClaim.Timestamp)+6, 0)) - _, err = s.app.OracleKeeper.CheckClaim(s.ctx, &msgClaim) - s.Require().NotNil(err, "error should not be nil") - s.Require().Contains(err.Error(), fmt.Sprintf("relayer(%s) is not in turn", validators[0].RelayerAddress)) - // wrong validator set wrongValBitSet := bitset.New(256) for i := 0; i < 10; i++ { @@ -231,7 +225,7 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { AggSignature: []byte("test sig"), }, 1992, - false, + true, "", }, // right validator in backoff time @@ -252,15 +246,15 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { }, } - for _, test := range tests { + for idx, test := range tests { s.ctx = s.ctx.WithBlockTime(time.Unix(test.blockTime, 0)) isInturn, err := s.app.OracleKeeper.IsRelayerInturn(s.ctx, vals, &test.claimMsg) if test.expectedPass { s.Require().Nil(err) - s.Require().True(isInturn) + s.Require().True(isInturn, fmt.Sprintf("test case %d should be right", idx)) } else { - s.Require().False(isInturn) + s.Require().False(isInturn, fmt.Sprintf("test case %d should be false", idx)) } } } From f0bb8bf4fb528264f642913f7ab36dec73bc037d Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 11 Jan 2023 15:58:16 +0800 Subject: [PATCH 41/50] fix lint errors --- x/oracle/keeper/keeper.go | 2 +- x/oracle/keeper/msg_server.go | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 671553a5ad..24ab180964 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -106,7 +106,7 @@ func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Valid curTime := ctx.BlockTime().Unix() relayerTimeout, relayerBackoffTime := k.GetRelayerParam(ctx) - // inturn validator can always relay pacakge + // inturn validator can always relay package if uint64(validatorIndex) == inturnValidatorIndex { return true, nil } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 29f2ee76bf..2c6498ccaf 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -83,6 +83,9 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg } err = distributeReward(ctx, k.oracleKeeper, req.FromAddress, signedRelayers, totalRelayerFee) + if err != nil { + return nil, err + } ctx.EventManager().EmitTypedEvents(events...) From fdc3a0f1cdb33b47cad97578c1e558b841134d7e Mon Sep 17 00:00:00 2001 From: yutianwu Date: Wed, 11 Jan 2023 16:40:18 +0800 Subject: [PATCH 42/50] fix unit tests --- x/oracle/keeper/msg_server.go | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 2c6498ccaf..43cce80bc0 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -94,6 +94,11 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg // distributeReward will distribute reward to relayers func distributeReward(ctx sdk.Context, oracleKeeper Keeper, relayer string, signedRelayers []string, relayerFee *big.Int) error { + if relayerFee.Cmp(big.NewInt(0)) <= 0 { + oracleKeeper.Logger(ctx).Info("total relayer fee is zero") + return nil + } + relayerAddr, err := sdk.AccAddressFromHexUnsafe(relayer) if err != nil { return sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("relayer address (%s) is invalid", relayer)) @@ -122,24 +127,32 @@ func distributeReward(ctx sdk.Context, oracleKeeper Keeper, relayer string, sign } bondDenom := oracleKeeper.StakingKeeper.BondDenom(ctx) - for idx := range otherRelayers { + if otherRelayerReward.Cmp(big.NewInt(0)) > 0 { + for idx := range otherRelayers { + err = oracleKeeper.BankKeeper.SendCoinsFromModuleToAccount(ctx, + crosschaintypes.ModuleName, + otherRelayers[idx], + sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(otherRelayerReward)}}, + ) + if err != nil { + return err + } + totalDistributed = totalDistributed.Add(totalDistributed, otherRelayerReward) + } + } + + remainingReward := relayerFee.Sub(relayerFee, totalDistributed) + if remainingReward.Cmp(big.NewInt(0)) > 0 { err = oracleKeeper.BankKeeper.SendCoinsFromModuleToAccount(ctx, crosschaintypes.ModuleName, - otherRelayers[idx], - sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(otherRelayerReward)}}, + relayerAddr, + sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(remainingReward)}}, ) if err != nil { return err } - totalDistributed = totalDistributed.Add(totalDistributed, otherRelayerReward) } - remainingReward := relayerFee.Sub(relayerFee, totalDistributed) - err = oracleKeeper.BankKeeper.SendCoinsFromModuleToAccount(ctx, - crosschaintypes.ModuleName, - relayerAddr, - sdk.Coins{sdk.Coin{Denom: bondDenom, Amount: sdk.NewIntFromBigInt(remainingReward)}}, - ) return err } From e7b443979a3822cf900d5609aee668a855e157f1 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 13 Jan 2023 13:40:44 +0800 Subject: [PATCH 43/50] fix comments --- proto/cosmos/crosschain/v1/event.proto | 1 + proto/cosmos/oracle/v1/event.proto | 4 +- server/util.go | 3 + types/cross_chain.go | 18 ++-- x/crosschain/keeper/keeper.go | 21 ++--- x/crosschain/types/event.pb.go | 110 ++++++++++++++++++------- x/crosschain/types/genesis.go | 14 ++++ x/crosschain/types/params.go | 2 +- x/oracle/keeper/keeper.go | 8 +- x/oracle/keeper/keeper_test.go | 8 +- x/oracle/keeper/msg_server.go | 8 +- x/oracle/keeper/msg_server_test.go | 4 +- x/oracle/types/event.pb.go | 88 ++++++++++---------- x/oracle/types/expected_keepers.go | 2 +- 14 files changed, 182 insertions(+), 109 deletions(-) diff --git a/proto/cosmos/crosschain/v1/event.proto b/proto/cosmos/crosschain/v1/event.proto index eae3023011..78d3cfb898 100644 --- a/proto/cosmos/crosschain/v1/event.proto +++ b/proto/cosmos/crosschain/v1/event.proto @@ -14,4 +14,5 @@ message EventCrossChain { uint64 timestamp = 6; bytes package_load = 7; string relayer_fee = 8; + string ack_relayer_fee = 9; } diff --git a/proto/cosmos/oracle/v1/event.proto b/proto/cosmos/oracle/v1/event.proto index 1f99602d2e..974f7271da 100644 --- a/proto/cosmos/oracle/v1/event.proto +++ b/proto/cosmos/oracle/v1/event.proto @@ -15,6 +15,6 @@ message EventPackageClaim { int64 send_sequence = 6; bool crash = 7; string error_msg = 8; - string syn_relay_fee = 9; - string ack_relay_fee = 10; + string relayer_fee = 9; + string ack_relayer_fee = 10; } \ No newline at end of file diff --git a/server/util.go b/server/util.go index d9e4f930ba..5be3643ecc 100644 --- a/server/util.go +++ b/server/util.go @@ -194,6 +194,9 @@ func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error { // viperCfg object. func interceptConfigs(rootViper *viper.Viper, customAppTemplate string, customConfig interface{}, tmConfig *tmcfg.Config) (*tmcfg.Config, error) { rootDir := rootViper.GetString(flags.FlagHome) + + println("root dir: ", rootDir) + configPath := filepath.Join(rootDir, "config") tmCfgFile := filepath.Join(configPath, "config.toml") diff --git a/types/cross_chain.go b/types/cross_chain.go index a2404043a1..d569a9cf6e 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -70,10 +70,12 @@ func GetPackageHeaderLength(packageType CrossChainPackageType) int { } type PackageHeader struct { - PackageType CrossChainPackageType - Timestamp uint64 - SynRelayerFee *big.Int // syn relayer fee is the relayer fee paid to relayer src source chain to dest chain - AckRelayerFee *big.Int // ack relayer fee is the relayer fee paid to relayer for the ack or fail ack package if there is any + PackageType CrossChainPackageType + Timestamp uint64 + RelayerFee *big.Int // relayer fee is the relayer fee paid to relayer src source chain to dest chain + // ack relayer fee is the relayer fee paid to relayer for the ack or fail ack package if there is any + // Ack and FailAck packages don't have ack relayer fee, since there is no corresponding ack or fail ack packages + AckRelayerFee *big.Int } var NilAckRelayerFee = big.NewInt(0) // For ack packages, the ack relayer fee should be nil, and it would not be encoded into package header @@ -86,8 +88,8 @@ func EncodePackageHeader(header PackageHeader) []byte { binary.BigEndian.PutUint64(timestampBytes, header.Timestamp) copy(packageHeader[PackageTypeLength:PackageTypeLength+TimestampLength], timestampBytes) - synRelayerFeeLength := len(header.SynRelayerFee.Bytes()) - copy(packageHeader[AckPackageHeaderLength-synRelayerFeeLength:AckPackageHeaderLength], header.SynRelayerFee.Bytes()) + relayerFeeLength := len(header.RelayerFee.Bytes()) + copy(packageHeader[AckPackageHeaderLength-relayerFeeLength:AckPackageHeaderLength], header.RelayerFee.Bytes()) // add ack relayer fee to header for syn package if header.PackageType == SynCrossChainPackageType { @@ -116,12 +118,12 @@ func DecodePackageHeader(packageHeader []byte) (PackageHeader, error) { timestamp := binary.BigEndian.Uint64(packageHeader[PackageTypeLength : PackageTypeLength+TimestampLength]) - synRelayFee := big.NewInt(0).SetBytes(packageHeader[PackageTypeLength+TimestampLength : AckPackageHeaderLength]) + relayerFee := big.NewInt(0).SetBytes(packageHeader[PackageTypeLength+TimestampLength : AckPackageHeaderLength]) header := PackageHeader{ PackageType: packageType, Timestamp: timestamp, - SynRelayerFee: synRelayFee, + RelayerFee: relayerFee, AckRelayerFee: big.NewInt(0), } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index c01210e3f5..14c422685c 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -80,7 +80,7 @@ func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { // CreateRawIBCPackageWithFee creates a cross chain package with given cross chain fee func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, + packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee *big.Int, ackRelayerFee *big.Int, ) (uint64, error) { if packageType == sdk.SynCrossChainPackageType && k.GetChannelSendPermission(ctx, k.GetDestChainID(), channelID) != sdk.ChannelAllow { return 0, fmt.Errorf("channel %d is not allowed to write syn package", channelID) @@ -97,7 +97,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.Channe packageHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ PackageType: packageType, Timestamp: uint64(ctx.BlockTime().Unix()), - SynRelayerFee: synRelayerFee, + RelayerFee: relayerFee, AckRelayerFee: ackRelayerFee, }) @@ -106,14 +106,15 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.Channe k.IncrSendSequence(ctx, channelID) err := ctx.EventManager().EmitTypedEvent(&types.EventCrossChain{ - SrcChainId: uint32(k.GetSrcChainID()), - DestChainId: uint32(k.GetDestChainID()), - ChannelId: uint32(channelID), - Sequence: sequence, - PackageType: uint32(packageType), - Timestamp: uint64(ctx.BlockTime().Unix()), - PackageLoad: packageLoad, - RelayerFee: synRelayerFee.String(), + SrcChainId: uint32(k.GetSrcChainID()), + DestChainId: uint32(k.GetDestChainID()), + ChannelId: uint32(channelID), + Sequence: sequence, + PackageType: uint32(packageType), + Timestamp: uint64(ctx.BlockTime().Unix()), + PackageLoad: packageLoad, + RelayerFee: relayerFee.String(), + AckRelayerFee: ackRelayerFee.String(), }) if err != nil { return 0, err diff --git a/x/crosschain/types/event.pb.go b/x/crosschain/types/event.pb.go index 2ff60cd1d1..e16e3c85b8 100644 --- a/x/crosschain/types/event.pb.go +++ b/x/crosschain/types/event.pb.go @@ -24,14 +24,15 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package // EventCrossChain is emitted when there is a cross chain package created type EventCrossChain struct { - SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` - DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` - ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` - Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` - PackageType uint32 `protobuf:"varint,5,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` - Timestamp uint64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - PackageLoad []byte `protobuf:"bytes,7,opt,name=package_load,json=packageLoad,proto3" json:"package_load,omitempty"` - RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` + SrcChainId uint32 `protobuf:"varint,1,opt,name=src_chain_id,json=srcChainId,proto3" json:"src_chain_id,omitempty"` + DestChainId uint32 `protobuf:"varint,2,opt,name=dest_chain_id,json=destChainId,proto3" json:"dest_chain_id,omitempty"` + ChannelId uint32 `protobuf:"varint,3,opt,name=channel_id,json=channelId,proto3" json:"channel_id,omitempty"` + Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` + PackageType uint32 `protobuf:"varint,5,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` + Timestamp uint64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` + PackageLoad []byte `protobuf:"bytes,7,opt,name=package_load,json=packageLoad,proto3" json:"package_load,omitempty"` + RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` + AckRelayerFee string `protobuf:"bytes,9,opt,name=ack_relayer_fee,json=ackRelayerFee,proto3" json:"ack_relayer_fee,omitempty"` } func (m *EventCrossChain) Reset() { *m = EventCrossChain{} } @@ -123,6 +124,13 @@ func (m *EventCrossChain) GetRelayerFee() string { return "" } +func (m *EventCrossChain) GetAckRelayerFee() string { + if m != nil { + return m.AckRelayerFee + } + return "" +} + func init() { proto.RegisterType((*EventCrossChain)(nil), "cosmos.crosschain.v1.EventCrossChain") } @@ -130,27 +138,28 @@ func init() { func init() { proto.RegisterFile("cosmos/crosschain/v1/event.proto", fileDescriptor_2a5a3ba75f5dd2c3) } var fileDescriptor_2a5a3ba75f5dd2c3 = []byte{ - // 309 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0x91, 0xcd, 0x4e, 0x32, 0x31, - 0x14, 0x86, 0x29, 0x1f, 0x1f, 0xc2, 0x01, 0x62, 0xd2, 0xb8, 0x98, 0x18, 0x1d, 0x47, 0x56, 0xb3, - 0x71, 0x1a, 0xe2, 0x1d, 0x48, 0x34, 0x21, 0x71, 0x45, 0x5c, 0xb9, 0x99, 0x94, 0xf6, 0x08, 0x13, - 0x98, 0xe9, 0xd8, 0x16, 0x22, 0x77, 0xe1, 0xce, 0x5b, 0x72, 0xc9, 0xd2, 0xa5, 0x81, 0x1b, 0x31, - 0x2d, 0xbf, 0xab, 0xa6, 0x4f, 0x9f, 0xbe, 0x39, 0x39, 0x2f, 0x44, 0x42, 0x99, 0x5c, 0x19, 0x26, - 0xb4, 0x32, 0x46, 0x4c, 0x78, 0x56, 0xb0, 0x45, 0x8f, 0xe1, 0x02, 0x0b, 0x9b, 0x94, 0x5a, 0x59, - 0x45, 0x2f, 0xb6, 0x46, 0x72, 0x34, 0x92, 0x45, 0xaf, 0xfb, 0x55, 0x85, 0xf3, 0x47, 0x67, 0xf5, - 0x1d, 0xee, 0x3b, 0x4c, 0x23, 0x68, 0x1b, 0x2d, 0x52, 0xef, 0xa4, 0x99, 0x0c, 0x48, 0x44, 0xe2, - 0xce, 0x10, 0x8c, 0x16, 0xfe, 0x7d, 0x20, 0x69, 0x17, 0x3a, 0x12, 0x8d, 0x3d, 0x2a, 0x55, 0xaf, - 0xb4, 0x1c, 0xdc, 0x3b, 0xd7, 0x00, 0x62, 0xc2, 0x8b, 0x02, 0x67, 0x4e, 0xf8, 0xe7, 0x85, 0xe6, - 0x8e, 0x0c, 0x24, 0xbd, 0x84, 0x86, 0xc1, 0xf7, 0x39, 0x16, 0x02, 0x83, 0x5a, 0x44, 0xe2, 0xda, - 0xf0, 0x70, 0xa7, 0xb7, 0xd0, 0x2e, 0xb9, 0x98, 0xf2, 0x31, 0xa6, 0x76, 0x59, 0x62, 0xf0, 0x7f, - 0x9b, 0xbe, 0x63, 0x2f, 0xcb, 0x12, 0xe9, 0x15, 0x34, 0x6d, 0x96, 0xa3, 0xb1, 0x3c, 0x2f, 0x83, - 0xba, 0xff, 0x7f, 0x04, 0xa7, 0x01, 0x33, 0xc5, 0x65, 0x70, 0x16, 0x91, 0xb8, 0x7d, 0x08, 0x78, - 0x56, 0x5c, 0xd2, 0x1b, 0x68, 0x69, 0x9c, 0xf1, 0x25, 0xea, 0xf4, 0x0d, 0x31, 0x68, 0x44, 0x24, - 0x6e, 0x0e, 0x61, 0x87, 0x9e, 0x10, 0x1f, 0x06, 0xdf, 0xeb, 0x90, 0xac, 0xd6, 0x21, 0xf9, 0x5d, - 0x87, 0xe4, 0x73, 0x13, 0x56, 0x56, 0x9b, 0xb0, 0xf2, 0xb3, 0x09, 0x2b, 0xaf, 0x6c, 0x9c, 0xd9, - 0xc9, 0x7c, 0x94, 0x08, 0x95, 0xb3, 0xfd, 0xda, 0xfd, 0x71, 0x67, 0xe4, 0x94, 0x7d, 0x9c, 0x76, - 0xe0, 0xc6, 0x37, 0xa3, 0xba, 0x6f, 0xe0, 0xfe, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x98, 0x73, 0x1c, - 0xaf, 0xa5, 0x01, 0x00, 0x00, + // 326 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0xd1, 0x4f, 0x4f, 0xfa, 0x30, + 0x18, 0xc0, 0x71, 0xca, 0x8f, 0x1f, 0xb2, 0x07, 0x08, 0x49, 0xe3, 0x61, 0x31, 0x3a, 0x27, 0x07, + 0xb3, 0x8b, 0x5b, 0x88, 0xef, 0x40, 0xa2, 0x09, 0x89, 0xa7, 0xc5, 0x93, 0x97, 0xa5, 0xb4, 0x8f, + 0xb0, 0x8c, 0xad, 0x73, 0x2d, 0x44, 0xde, 0x85, 0xef, 0xc8, 0xab, 0x47, 0x8e, 0x1e, 0x0d, 0xbc, + 0x11, 0xd3, 0xf2, 0xf7, 0xb4, 0xec, 0xdb, 0x4f, 0x9f, 0xa4, 0x79, 0xc0, 0xe7, 0x52, 0xe5, 0x52, + 0x45, 0xbc, 0x92, 0x4a, 0xf1, 0x29, 0x4b, 0x8b, 0x68, 0x31, 0x88, 0x70, 0x81, 0x85, 0x0e, 0xcb, + 0x4a, 0x6a, 0x49, 0xcf, 0xb7, 0x22, 0x3c, 0x8a, 0x70, 0x31, 0xe8, 0x7f, 0xd5, 0xa1, 0xf7, 0x68, + 0xd4, 0xd0, 0xe4, 0xa1, 0xc9, 0xd4, 0x87, 0x8e, 0xaa, 0x78, 0x62, 0x4d, 0x92, 0x0a, 0x97, 0xf8, + 0x24, 0xe8, 0xc6, 0xa0, 0x2a, 0x6e, 0xcf, 0x47, 0x82, 0xf6, 0xa1, 0x2b, 0x50, 0xe9, 0x23, 0xa9, + 0x5b, 0xd2, 0x36, 0x71, 0x6f, 0xae, 0x00, 0xf8, 0x94, 0x15, 0x05, 0xce, 0x0c, 0xf8, 0x67, 0x81, + 0xb3, 0x2b, 0x23, 0x41, 0x2f, 0xa0, 0xa5, 0xf0, 0x7d, 0x8e, 0x05, 0x47, 0xb7, 0xe1, 0x93, 0xa0, + 0x11, 0x1f, 0xfe, 0xe9, 0x0d, 0x74, 0x4a, 0xc6, 0x33, 0x36, 0xc1, 0x44, 0x2f, 0x4b, 0x74, 0xff, + 0x6f, 0xa7, 0xef, 0xda, 0xcb, 0xb2, 0x44, 0x7a, 0x09, 0x8e, 0x4e, 0x73, 0x54, 0x9a, 0xe5, 0xa5, + 0xdb, 0xb4, 0xf7, 0x8f, 0xe1, 0x74, 0xc0, 0x4c, 0x32, 0xe1, 0x9e, 0xf9, 0x24, 0xe8, 0x1c, 0x06, + 0x3c, 0x4b, 0x26, 0xe8, 0x35, 0xb4, 0x2b, 0x9c, 0xb1, 0x25, 0x56, 0xc9, 0x1b, 0xa2, 0xdb, 0xf2, + 0x49, 0xe0, 0xc4, 0xb0, 0x4b, 0x4f, 0x88, 0xf4, 0x16, 0x7a, 0x8c, 0x67, 0xc9, 0x29, 0x72, 0x2c, + 0xea, 0x32, 0x9e, 0xc5, 0x07, 0xf7, 0x30, 0xfa, 0x5e, 0x7b, 0x64, 0xb5, 0xf6, 0xc8, 0xef, 0xda, + 0x23, 0x9f, 0x1b, 0xaf, 0xb6, 0xda, 0x78, 0xb5, 0x9f, 0x8d, 0x57, 0x7b, 0x8d, 0x26, 0xa9, 0x9e, + 0xce, 0xc7, 0x21, 0x97, 0x79, 0xb4, 0x5f, 0x8f, 0xfd, 0xdc, 0x29, 0x91, 0x45, 0x1f, 0xa7, 0xbb, + 0x32, 0xcf, 0x54, 0xe3, 0xa6, 0xdd, 0xd4, 0xfd, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3a, 0x57, + 0x60, 0xd9, 0xcd, 0x01, 0x00, 0x00, } func (m *EventCrossChain) Marshal() (dAtA []byte, err error) { @@ -173,6 +182,13 @@ func (m *EventCrossChain) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l + if len(m.AckRelayerFee) > 0 { + i -= len(m.AckRelayerFee) + copy(dAtA[i:], m.AckRelayerFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.AckRelayerFee))) + i-- + dAtA[i] = 0x4a + } if len(m.RelayerFee) > 0 { i -= len(m.RelayerFee) copy(dAtA[i:], m.RelayerFee) @@ -263,6 +279,10 @@ func (m *EventCrossChain) Size() (n int) { if l > 0 { n += 1 + l + sovEvent(uint64(l)) } + l = len(m.AckRelayerFee) + if l > 0 { + n += 1 + l + sovEvent(uint64(l)) + } return n } @@ -481,6 +501,38 @@ func (m *EventCrossChain) Unmarshal(dAtA []byte) error { } m.RelayerFee = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex + case 9: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AckRelayerFee", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowEvent + } + 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 ErrInvalidLengthEvent + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthEvent + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AckRelayerFee = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipEvent(dAtA[iNdEx:]) diff --git a/x/crosschain/types/genesis.go b/x/crosschain/types/genesis.go index 99947edb7e..889659066b 100644 --- a/x/crosschain/types/genesis.go +++ b/x/crosschain/types/genesis.go @@ -1,5 +1,10 @@ package types +import ( + "fmt" + "math/big" +) + // NewGenesisState creates a new GenesisState object func NewGenesisState( params Params, @@ -18,5 +23,14 @@ func DefaultGenesisState() *GenesisState { // ValidateGenesis validates the cross chain genesis parameters func ValidateGenesis(data GenesisState) error { + balance, valid := big.NewInt(0).SetString(data.Params.InitModuleBalance, 10) + if !valid { + return fmt.Errorf("invalid module balance, is %s", data.Params.InitModuleBalance) + } + + if balance.Cmp(big.NewInt(0)) < 0 { + return fmt.Errorf("init module balance should be positive, is %s", balance.String()) + } + return nil } diff --git a/x/crosschain/types/params.go b/x/crosschain/types/params.go index 9ec046504a..04ad47c18a 100644 --- a/x/crosschain/types/params.go +++ b/x/crosschain/types/params.go @@ -7,7 +7,7 @@ import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) -const DefaultInitModuleBalance string = "1000000000" +const DefaultInitModuleBalance string = "1000000000000000000000000000" var KeyParamInitModuleBalance = []byte("InitModuleBalance") diff --git a/x/oracle/keeper/keeper.go b/x/oracle/keeper/keeper.go index 24ab180964..c5bc8a2c13 100644 --- a/x/oracle/keeper/keeper.go +++ b/x/oracle/keeper/keeper.go @@ -81,8 +81,8 @@ func (k Keeper) GetRelayerRewardShare(ctx sdk.Context) uint32 { return relayerRewardShare } -// IsRelayerInturn checks the inturn status of the relayer -func (k Keeper) IsRelayerInturn(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { +// IsRelayerValid returns true if the relayer is valid and allowed to send the claim message +func (k Keeper) IsRelayerValid(ctx sdk.Context, validators []stakingtypes.Validator, claim *types.MsgClaim) (bool, error) { fromAddress, err := sdk.AccAddressFromHexUnsafe(claim.FromAddress) if err != nil { return false, sdkerrors.Wrapf(types.ErrInvalidAddress, fmt.Sprintf("from address (%s) is invalid", claim.FromAddress)) @@ -127,11 +127,11 @@ func (k Keeper) CheckClaim(ctx sdk.Context, claim *types.MsgClaim) ([]string, er } validators := historicalInfo.Valset - inturn, err := k.IsRelayerInturn(ctx, validators, claim) + isValid, err := k.IsRelayerValid(ctx, validators, claim) if err != nil { return nil, err } - if !inturn { + if !isValid { return nil, sdkerrors.Wrapf(types.ErrRelayerNotInTurn, fmt.Sprintf("relayer(%s) is not in turn", claim.FromAddress)) } diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 6623c9a9df..6ef21a8bf3 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -142,7 +142,7 @@ func (s *TestSuite) TestProcessClaim() { s.Require().Contains(err.Error(), "BLS signature converts failed") } -func (s *TestSuite) TestKeeper_IsValidatorInturn() { +func (s *TestSuite) TestKeeper_IsRelayerValid() { s.app.OracleKeeper.SetParams(s.ctx, types.Params{ RelayerTimeout: 5, RelayerBackoffTime: 3, @@ -248,13 +248,13 @@ func (s *TestSuite) TestKeeper_IsValidatorInturn() { for idx, test := range tests { s.ctx = s.ctx.WithBlockTime(time.Unix(test.blockTime, 0)) - isInturn, err := s.app.OracleKeeper.IsRelayerInturn(s.ctx, vals, &test.claimMsg) + isValid, err := s.app.OracleKeeper.IsRelayerValid(s.ctx, vals, &test.claimMsg) if test.expectedPass { s.Require().Nil(err) - s.Require().True(isInturn, fmt.Sprintf("test case %d should be right", idx)) + s.Require().True(isValid, fmt.Sprintf("test case %d should be right", idx)) } else { - s.Require().False(isInturn, fmt.Sprintf("test case %d should be false", idx)) + s.Require().False(isValid, fmt.Sprintf("test case %d should be false", idx)) } } } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 43cce80bc0..760cab1f61 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -191,7 +191,7 @@ func handlePackage( } cacheCtx, write := ctx.CacheContext() - crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageHeader.PackageType, packageHeader.SynRelayerFee) + crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageHeader.PackageType, packageHeader.RelayerFee) if result.IsOk() { write() } @@ -234,13 +234,13 @@ func handlePackage( PackageType: uint32(packageHeader.PackageType), ReceiveSequence: pack.Sequence, SendSequence: sendSequence, - SynRelayFee: packageHeader.SynRelayerFee.String(), - AckRelayFee: packageHeader.AckRelayerFee.String(), + RelayerFee: packageHeader.RelayerFee.String(), + AckRelayerFee: packageHeader.AckRelayerFee.String(), Crash: crash, ErrorMsg: result.ErrMsg(), } - return packageHeader.SynRelayerFee, claimEvent, nil + return packageHeader.RelayerFee, claimEvent, nil } func executeClaim( diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index a935487a68..cf995cb675 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -53,7 +53,7 @@ func (s *TestSuite) TestClaim() { payloadHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ PackageType: sdk.SynCrossChainPackageType, Timestamp: 1992, - SynRelayerFee: big.NewInt(1), + RelayerFee: big.NewInt(1), AckRelayerFee: big.NewInt(1), }) @@ -156,7 +156,7 @@ func (s *TestSuite) TestInvalidClaim() { payloadHeader := sdk.EncodePackageHeader(sdk.PackageHeader{ PackageType: sdk.SynCrossChainPackageType, Timestamp: 1993, - SynRelayerFee: big.NewInt(1), + RelayerFee: big.NewInt(1), AckRelayerFee: big.NewInt(1), }) testPackage := types.Package{ diff --git a/x/oracle/types/event.pb.go b/x/oracle/types/event.pb.go index 4220a3695e..9fb4ce677c 100644 --- a/x/oracle/types/event.pb.go +++ b/x/oracle/types/event.pb.go @@ -32,8 +32,8 @@ type EventPackageClaim struct { SendSequence int64 `protobuf:"varint,6,opt,name=send_sequence,json=sendSequence,proto3" json:"send_sequence,omitempty"` Crash bool `protobuf:"varint,7,opt,name=crash,proto3" json:"crash,omitempty"` ErrorMsg string `protobuf:"bytes,8,opt,name=error_msg,json=errorMsg,proto3" json:"error_msg,omitempty"` - SynRelayFee string `protobuf:"bytes,9,opt,name=syn_relay_fee,json=synRelayFee,proto3" json:"syn_relay_fee,omitempty"` - AckRelayFee string `protobuf:"bytes,10,opt,name=ack_relay_fee,json=ackRelayFee,proto3" json:"ack_relay_fee,omitempty"` + RelayerFee string `protobuf:"bytes,9,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` + AckRelayerFee string `protobuf:"bytes,10,opt,name=ack_relayer_fee,json=ackRelayerFee,proto3" json:"ack_relayer_fee,omitempty"` } func (m *EventPackageClaim) Reset() { *m = EventPackageClaim{} } @@ -125,16 +125,16 @@ func (m *EventPackageClaim) GetErrorMsg() string { return "" } -func (m *EventPackageClaim) GetSynRelayFee() string { +func (m *EventPackageClaim) GetRelayerFee() string { if m != nil { - return m.SynRelayFee + return m.RelayerFee } return "" } -func (m *EventPackageClaim) GetAckRelayFee() string { +func (m *EventPackageClaim) GetAckRelayerFee() string { if m != nil { - return m.AckRelayFee + return m.AckRelayerFee } return "" } @@ -146,30 +146,30 @@ func init() { func init() { proto.RegisterFile("cosmos/oracle/v1/event.proto", fileDescriptor_3e254cedc4112fb0) } var fileDescriptor_3e254cedc4112fb0 = []byte{ - // 353 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0xd1, 0xcd, 0x4e, 0xab, 0x40, - 0x14, 0xc0, 0xf1, 0x4e, 0xbf, 0x6e, 0x99, 0xb6, 0xb9, 0x95, 0xb8, 0x20, 0x51, 0x09, 0xd6, 0x0d, - 0xc6, 0x08, 0x69, 0x7c, 0x03, 0x9b, 0x9a, 0x74, 0x61, 0x62, 0xd0, 0x95, 0x1b, 0x32, 0x1d, 0x8e, - 0x40, 0x80, 0x01, 0x67, 0x28, 0x91, 0xb7, 0xf0, 0xb1, 0x5c, 0x76, 0xe9, 0xd2, 0xb4, 0x89, 0xcf, - 0x61, 0x06, 0xa8, 0x75, 0x45, 0xf8, 0x9f, 0x5f, 0x20, 0x33, 0x07, 0x9f, 0xd2, 0x54, 0x24, 0xa9, - 0xb0, 0x53, 0x4e, 0x68, 0x0c, 0x76, 0x31, 0xb3, 0xa1, 0x00, 0x96, 0x5b, 0x19, 0x4f, 0xf3, 0x54, - 0x9d, 0xd4, 0x53, 0xab, 0x9e, 0x5a, 0xc5, 0x6c, 0xfa, 0xdd, 0xc6, 0x47, 0x0b, 0x29, 0x1e, 0x08, - 0x8d, 0x88, 0x0f, 0xf3, 0x98, 0x84, 0x89, 0x6a, 0xe0, 0x91, 0xe0, 0xd4, 0xa5, 0x01, 0x09, 0x99, - 0x1b, 0x7a, 0x1a, 0x32, 0x90, 0x39, 0x76, 0xb0, 0xe0, 0x74, 0x2e, 0xd3, 0xd2, 0x53, 0xa7, 0x78, - 0xec, 0x81, 0xc8, 0x0f, 0xa4, 0x5d, 0x91, 0xa1, 0x8c, 0x7b, 0x73, 0x86, 0x31, 0x0d, 0x08, 0x63, - 0x10, 0x4b, 0xd0, 0xa9, 0x80, 0xd2, 0x94, 0xa5, 0xa7, 0x9e, 0xe3, 0x51, 0x56, 0xff, 0xd4, 0xcd, - 0xcb, 0x0c, 0xb4, 0x6e, 0xfd, 0x85, 0xa6, 0x3d, 0x95, 0x19, 0xa8, 0x97, 0x78, 0xc2, 0x81, 0x42, - 0x58, 0x80, 0x2b, 0xe0, 0x75, 0x0d, 0x8c, 0x82, 0xd6, 0x33, 0x90, 0xd9, 0x75, 0xfe, 0x37, 0xfd, - 0xb1, 0xc9, 0xea, 0x05, 0x1e, 0x0b, 0x60, 0xde, 0xc1, 0xf5, 0x0d, 0x64, 0x76, 0x9c, 0x91, 0x8c, - 0xbf, 0xe8, 0x18, 0xf7, 0x28, 0x27, 0x22, 0xd0, 0xfe, 0x19, 0xc8, 0x1c, 0x38, 0xf5, 0x8b, 0x7a, - 0x82, 0x15, 0xe0, 0x3c, 0xe5, 0x6e, 0x22, 0x7c, 0x6d, 0x60, 0x20, 0x53, 0x71, 0x06, 0x55, 0xb8, - 0x17, 0xbe, 0x3c, 0xa8, 0x28, 0x99, 0xcb, 0x21, 0x26, 0xa5, 0xfb, 0x02, 0xa0, 0x29, 0x15, 0x18, - 0x8a, 0x92, 0x39, 0xb2, 0xdd, 0x01, 0x48, 0x43, 0x68, 0xf4, 0xc7, 0xe0, 0xda, 0x10, 0x1a, 0xed, - 0xcd, 0xed, 0xe2, 0x63, 0xab, 0xa3, 0xcd, 0x56, 0x47, 0x5f, 0x5b, 0x1d, 0xbd, 0xef, 0xf4, 0xd6, - 0x66, 0xa7, 0xb7, 0x3e, 0x77, 0x7a, 0xeb, 0xf9, 0xca, 0x0f, 0xf3, 0x60, 0xbd, 0xb2, 0x68, 0x9a, - 0xd8, 0xcd, 0xf6, 0xea, 0xc7, 0xb5, 0xf0, 0x22, 0xfb, 0x6d, 0xbf, 0x4a, 0x79, 0x47, 0x62, 0xd5, - 0xaf, 0x16, 0x79, 0xf3, 0x13, 0x00, 0x00, 0xff, 0xff, 0xec, 0xb3, 0x85, 0x18, 0xe8, 0x01, 0x00, - 0x00, + // 357 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0xd1, 0xcb, 0x6a, 0xdb, 0x40, + 0x14, 0x80, 0x61, 0x8f, 0x6f, 0xb5, 0x8e, 0x2d, 0xec, 0x0e, 0x5d, 0x08, 0xda, 0xaa, 0xaa, 0x0b, + 0x45, 0xa5, 0x54, 0xc2, 0xf4, 0x0d, 0x6a, 0x5c, 0xf0, 0xa2, 0x50, 0x94, 0xac, 0xb2, 0x11, 0xe3, + 0xd1, 0x89, 0x24, 0x74, 0xcd, 0x8c, 0x2c, 0xe2, 0xb7, 0xc8, 0x63, 0x65, 0xe9, 0x65, 0x96, 0xc1, + 0x5e, 0xe4, 0x35, 0x82, 0x2e, 0xb6, 0xb3, 0x12, 0xfa, 0xcf, 0xc7, 0x0c, 0xcc, 0x81, 0x4f, 0x3c, + 0x93, 0x49, 0x26, 0xed, 0x4c, 0x30, 0x1e, 0xa3, 0x5d, 0x2e, 0x6c, 0x2c, 0x31, 0x2d, 0xac, 0x5c, + 0x64, 0x45, 0x46, 0x67, 0xcd, 0xd4, 0x6a, 0xa6, 0x56, 0xb9, 0x98, 0xbf, 0x74, 0xe1, 0xfd, 0xaa, + 0x12, 0xff, 0x19, 0x8f, 0x98, 0x8f, 0xcb, 0x98, 0x85, 0x09, 0x35, 0x60, 0x22, 0x05, 0x77, 0x79, + 0xc0, 0xc2, 0xd4, 0x0d, 0x3d, 0x8d, 0x18, 0xc4, 0x54, 0x1d, 0x90, 0x82, 0x2f, 0xab, 0xb4, 0xf6, + 0xe8, 0x1c, 0x54, 0x0f, 0x65, 0x71, 0x21, 0xdd, 0x9a, 0x8c, 0xab, 0x78, 0x32, 0x9f, 0x01, 0x78, + 0xc0, 0xd2, 0x14, 0xe3, 0x0a, 0xf4, 0x6a, 0xa0, 0xb4, 0x65, 0xed, 0xd1, 0xaf, 0x30, 0xc9, 0x9b, + 0x4b, 0xdd, 0x62, 0x97, 0xa3, 0xd6, 0x6f, 0x4e, 0x68, 0xdb, 0xf5, 0x2e, 0x47, 0xfa, 0x03, 0x66, + 0x02, 0x39, 0x86, 0x25, 0xba, 0x12, 0xef, 0xb6, 0x98, 0x72, 0xd4, 0x06, 0x06, 0x31, 0xfb, 0xce, + 0xb4, 0xed, 0x57, 0x6d, 0xa6, 0xdf, 0x40, 0x95, 0x98, 0x7a, 0x17, 0x37, 0x34, 0x88, 0xd9, 0x73, + 0x26, 0x55, 0x3c, 0xa3, 0x0f, 0x30, 0xe0, 0x82, 0xc9, 0x40, 0x7b, 0x67, 0x10, 0x73, 0xe4, 0x34, + 0x3f, 0xf4, 0x23, 0x28, 0x28, 0x44, 0x26, 0xdc, 0x44, 0xfa, 0xda, 0xc8, 0x20, 0xa6, 0xe2, 0x8c, + 0xea, 0xf0, 0x4f, 0xfa, 0xf4, 0x0b, 0x8c, 0x05, 0xc6, 0x6c, 0x87, 0xc2, 0xbd, 0x45, 0xd4, 0x94, + 0x7a, 0x0c, 0x6d, 0xfa, 0x8b, 0x48, 0xbf, 0xc3, 0x94, 0xf1, 0xc8, 0x7d, 0x8b, 0xa0, 0x46, 0x2a, + 0xe3, 0x91, 0x73, 0x76, 0x7f, 0x56, 0x8f, 0x07, 0x9d, 0xec, 0x0f, 0x3a, 0x79, 0x3e, 0xe8, 0xe4, + 0xe1, 0xa8, 0x77, 0xf6, 0x47, 0xbd, 0xf3, 0x74, 0xd4, 0x3b, 0x37, 0x3f, 0xfd, 0xb0, 0x08, 0xb6, + 0x1b, 0x8b, 0x67, 0x89, 0xdd, 0xae, 0xaf, 0xf9, 0xfc, 0x92, 0x5e, 0x64, 0xdf, 0x9f, 0x76, 0x59, + 0x3d, 0x92, 0xdc, 0x0c, 0xeb, 0x4d, 0xfe, 0x7e, 0x0d, 0x00, 0x00, 0xff, 0xff, 0x2d, 0x9f, 0x98, + 0x8f, 0xe9, 0x01, 0x00, 0x00, } func (m *EventPackageClaim) Marshal() (dAtA []byte, err error) { @@ -192,17 +192,17 @@ func (m *EventPackageClaim) MarshalToSizedBuffer(dAtA []byte) (int, error) { _ = i var l int _ = l - if len(m.AckRelayFee) > 0 { - i -= len(m.AckRelayFee) - copy(dAtA[i:], m.AckRelayFee) - i = encodeVarintEvent(dAtA, i, uint64(len(m.AckRelayFee))) + if len(m.AckRelayerFee) > 0 { + i -= len(m.AckRelayerFee) + copy(dAtA[i:], m.AckRelayerFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.AckRelayerFee))) i-- dAtA[i] = 0x52 } - if len(m.SynRelayFee) > 0 { - i -= len(m.SynRelayFee) - copy(dAtA[i:], m.SynRelayFee) - i = encodeVarintEvent(dAtA, i, uint64(len(m.SynRelayFee))) + if len(m.RelayerFee) > 0 { + i -= len(m.RelayerFee) + copy(dAtA[i:], m.RelayerFee) + i = encodeVarintEvent(dAtA, i, uint64(len(m.RelayerFee))) i-- dAtA[i] = 0x4a } @@ -298,11 +298,11 @@ func (m *EventPackageClaim) Size() (n int) { if l > 0 { n += 1 + l + sovEvent(uint64(l)) } - l = len(m.SynRelayFee) + l = len(m.RelayerFee) if l > 0 { n += 1 + l + sovEvent(uint64(l)) } - l = len(m.AckRelayFee) + l = len(m.AckRelayerFee) if l > 0 { n += 1 + l + sovEvent(uint64(l)) } @@ -512,7 +512,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { iNdEx = postIndex case 9: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SynRelayFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field RelayerFee", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -540,11 +540,11 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.SynRelayFee = string(dAtA[iNdEx:postIndex]) + m.RelayerFee = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 10: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AckRelayFee", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field AckRelayerFee", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -572,7 +572,7 @@ func (m *EventPackageClaim) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.AckRelayFee = string(dAtA[iNdEx:postIndex]) + m.AckRelayerFee = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex default: iNdEx = preIndex diff --git a/x/oracle/types/expected_keepers.go b/x/oracle/types/expected_keepers.go index 0830b51582..7bbc49fd00 100644 --- a/x/oracle/types/expected_keepers.go +++ b/x/oracle/types/expected_keepers.go @@ -15,7 +15,7 @@ type StakingKeeper interface { type CrossChainKeeper interface { CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.ChannelID, - packageType sdk.CrossChainPackageType, packageLoad []byte, synRelayerFee *big.Int, ackRelayerFee *big.Int, + packageType sdk.CrossChainPackageType, packageLoad []byte, relayerFee *big.Int, ackRelayerFee *big.Int, ) (uint64, error) GetCrossChainApp(channelID sdk.ChannelID) sdk.CrossChainApplication GetSrcChainID() sdk.ChainID From b3d6bb5d1f39ed47c007f5b8eb698e0ff444fec5 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 13 Jan 2023 14:42:59 +0800 Subject: [PATCH 44/50] pass package header to cross chain app --- types/cross_chain.go | 6 +++--- x/crosschain/testutil/mockapp.go | 15 +++++++-------- x/oracle/keeper/msg_server.go | 15 +++++++-------- x/oracle/keeper/msg_server_test.go | 6 +++--- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/types/cross_chain.go b/types/cross_chain.go index d569a9cf6e..ddbe4542fd 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -31,10 +31,10 @@ func IsValidCrossChainPackageType(packageType CrossChainPackageType) bool { } type CrossChainApplication interface { - ExecuteSynPackage(ctx Context, payload []byte, relayerFee *big.Int) ExecuteResult - ExecuteAckPackage(ctx Context, payload []byte) ExecuteResult + ExecuteSynPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult + ExecuteAckPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult // When the ack application crash, payload is the payload of the origin package. - ExecuteFailAckPackage(ctx Context, payload []byte) ExecuteResult + ExecuteFailAckPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult } type ExecuteResult struct { diff --git a/x/crosschain/testutil/mockapp.go b/x/crosschain/testutil/mockapp.go index 0b09dc9adb..6d5a15de1d 100644 --- a/x/crosschain/testutil/mockapp.go +++ b/x/crosschain/testutil/mockapp.go @@ -3,7 +3,6 @@ package testutil import ( - "math/big" reflect "reflect" gomock "github.com/golang/mock/gomock" @@ -35,21 +34,21 @@ func (m *MockCrossChainApplication) EXPECT() *MockCrossChainApplicationMockRecor } // ExecuteSynPackage mocks base method -func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, payload []byte, relayerFee *big.Int) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "ExecuteSynPackage", ctx, payload, relayerFee) + ret := m.ctrl.Call(m, "ExecuteSynPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) return ret0 } // ExecuteSynPackage indicates an expected call of ExecuteSynPackage -func (mr *MockCrossChainApplicationMockRecorder) ExecuteSynPackage(ctx, payload, relayerFee interface{}) *gomock.Call { +func (mr *MockCrossChainApplicationMockRecorder) ExecuteSynPackage(ctx, header, payload, relayerFee interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteSynPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteSynPackage), ctx, payload, relayerFee) } // ExecuteAckPackage mocks base method -func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, payload []byte) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteAckPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) @@ -57,13 +56,13 @@ func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, payload } // ExecuteAckPackage indicates an expected call of ExecuteAckPackage -func (mr *MockCrossChainApplicationMockRecorder) ExecuteAckPackage(ctx, payload interface{}) *gomock.Call { +func (mr *MockCrossChainApplicationMockRecorder) ExecuteAckPackage(ctx, header, payload interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteAckPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteAckPackage), ctx, payload) } // ExecuteFailAckPackage mocks base method -func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, payload []byte) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteFailAckPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) @@ -71,7 +70,7 @@ func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, pay } // ExecuteFailAckPackage indicates an expected call of ExecuteFailAckPackage -func (mr *MockCrossChainApplicationMockRecorder) ExecuteFailAckPackage(ctx, payload interface{}) *gomock.Call { +func (mr *MockCrossChainApplicationMockRecorder) ExecuteFailAckPackage(ctx, header, payload interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ExecuteFailAckPackage", reflect.TypeOf((*MockCrossChainApplication)(nil).ExecuteFailAckPackage), ctx, payload) } diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 760cab1f61..db41520965 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -191,7 +191,7 @@ func handlePackage( } cacheCtx, write := ctx.CacheContext() - crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, packageHeader.PackageType, packageHeader.RelayerFee) + crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, &packageHeader) if result.IsOk() { write() } @@ -247,8 +247,7 @@ func executeClaim( ctx sdk.Context, app sdk.CrossChainApplication, payload []byte, - packageType sdk.CrossChainPackageType, - relayerFee *big.Int, + header *sdk.PackageHeader, ) (crash bool, result sdk.ExecuteResult) { defer func() { if r := recover(); r != nil { @@ -262,15 +261,15 @@ func executeClaim( } }() - switch packageType { + switch header.PackageType { case sdk.SynCrossChainPackageType: - result = app.ExecuteSynPackage(ctx, payload[sdk.SynPackageHeaderLength:], relayerFee) + result = app.ExecuteSynPackage(ctx, header, payload[sdk.SynPackageHeaderLength:]) case sdk.AckCrossChainPackageType: - result = app.ExecuteAckPackage(ctx, payload[sdk.AckPackageHeaderLength:]) + result = app.ExecuteAckPackage(ctx, header, payload[sdk.AckPackageHeaderLength:]) case sdk.FailAckCrossChainPackageType: - result = app.ExecuteFailAckPackage(ctx, payload[sdk.AckPackageHeaderLength:]) + result = app.ExecuteFailAckPackage(ctx, header, payload[sdk.AckPackageHeaderLength:]) default: - panic(fmt.Sprintf("receive unexpected package type %d", packageType)) + panic(fmt.Sprintf("receive unexpected package type %d", header.PackageType)) } return } diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index cf995cb675..1dd3fc3543 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -15,15 +15,15 @@ import ( type DummyCrossChainApp struct{} -func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, payload []byte, relayerFee *big.Int) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte, relayerFee *big.Int) sdk.ExecuteResult { return sdk.ExecuteResult{} } -func (ta *DummyCrossChainApp) ExecuteAckPackage(ctx sdk.Context, payload []byte) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteAckPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte) sdk.ExecuteResult { return sdk.ExecuteResult{} } -func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, payload []byte) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte) sdk.ExecuteResult { return sdk.ExecuteResult{} } From 6d61c738851a0aaa4cfb130c5674391b19b22f56 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 13 Jan 2023 14:58:31 +0800 Subject: [PATCH 45/50] enrich the context passed to cross chain app --- types/cross_chain.go | 11 ++++++++--- x/crosschain/testutil/mockapp.go | 6 +++--- x/oracle/keeper/msg_server.go | 18 ++++++++++++++---- 3 files changed, 25 insertions(+), 10 deletions(-) diff --git a/types/cross_chain.go b/types/cross_chain.go index ddbe4542fd..3a98517cda 100644 --- a/types/cross_chain.go +++ b/types/cross_chain.go @@ -31,10 +31,15 @@ func IsValidCrossChainPackageType(packageType CrossChainPackageType) bool { } type CrossChainApplication interface { - ExecuteSynPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult - ExecuteAckPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult + ExecuteSynPackage(ctx Context, appCtx *CrossChainAppContext, payload []byte) ExecuteResult + ExecuteAckPackage(ctx Context, header *CrossChainAppContext, payload []byte) ExecuteResult // When the ack application crash, payload is the payload of the origin package. - ExecuteFailAckPackage(ctx Context, header *PackageHeader, payload []byte) ExecuteResult + ExecuteFailAckPackage(ctx Context, header *CrossChainAppContext, payload []byte) ExecuteResult +} + +type CrossChainAppContext struct { + Sequence uint64 + Header *PackageHeader } type ExecuteResult struct { diff --git a/x/crosschain/testutil/mockapp.go b/x/crosschain/testutil/mockapp.go index 6d5a15de1d..9339fedc78 100644 --- a/x/crosschain/testutil/mockapp.go +++ b/x/crosschain/testutil/mockapp.go @@ -34,7 +34,7 @@ func (m *MockCrossChainApplication) EXPECT() *MockCrossChainApplicationMockRecor } // ExecuteSynPackage mocks base method -func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteSynPackage(ctx types.Context, appCtx *types.CrossChainAppContext, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteSynPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) @@ -48,7 +48,7 @@ func (mr *MockCrossChainApplicationMockRecorder) ExecuteSynPackage(ctx, header, } // ExecuteAckPackage mocks base method -func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteAckPackage(ctx types.Context, header *types.CrossChainAppContext, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteAckPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) @@ -62,7 +62,7 @@ func (mr *MockCrossChainApplicationMockRecorder) ExecuteAckPackage(ctx, header, } // ExecuteFailAckPackage mocks base method -func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, header *types.PackageHeader, payload []byte) types.ExecuteResult { +func (m *MockCrossChainApplication) ExecuteFailAckPackage(ctx types.Context, header *types.CrossChainAppContext, payload []byte) types.ExecuteResult { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ExecuteFailAckPackage", ctx, payload) ret0, _ := ret[0].(types.ExecuteResult) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index db41520965..09f5b34d44 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -191,7 +191,7 @@ func handlePackage( } cacheCtx, write := ctx.CacheContext() - crash, result := executeClaim(cacheCtx, crossChainApp, pack.Payload, &packageHeader) + crash, result := executeClaim(cacheCtx, crossChainApp, sequence, pack.Payload, &packageHeader) if result.IsOk() { write() } @@ -246,6 +246,7 @@ func handlePackage( func executeClaim( ctx sdk.Context, app sdk.CrossChainApplication, + sequence uint64, payload []byte, header *sdk.PackageHeader, ) (crash bool, result sdk.ExecuteResult) { @@ -263,11 +264,20 @@ func executeClaim( switch header.PackageType { case sdk.SynCrossChainPackageType: - result = app.ExecuteSynPackage(ctx, header, payload[sdk.SynPackageHeaderLength:]) + result = app.ExecuteSynPackage(ctx, &sdk.CrossChainAppContext{ + Sequence: sequence, + Header: header, + }, payload[sdk.SynPackageHeaderLength:]) case sdk.AckCrossChainPackageType: - result = app.ExecuteAckPackage(ctx, header, payload[sdk.AckPackageHeaderLength:]) + result = app.ExecuteAckPackage(ctx, &sdk.CrossChainAppContext{ + Sequence: sequence, + Header: header, + }, payload[sdk.AckPackageHeaderLength:]) case sdk.FailAckCrossChainPackageType: - result = app.ExecuteFailAckPackage(ctx, header, payload[sdk.AckPackageHeaderLength:]) + result = app.ExecuteFailAckPackage(ctx, &sdk.CrossChainAppContext{ + Sequence: sequence, + Header: header, + }, payload[sdk.AckPackageHeaderLength:]) default: panic(fmt.Sprintf("receive unexpected package type %d", header.PackageType)) } From e12c5ed9de2e1c14e3dd731b992df4fd2c2d92ee Mon Sep 17 00:00:00 2001 From: yutianwu Date: Fri, 13 Jan 2023 15:49:53 +0800 Subject: [PATCH 46/50] fix lint error --- x/oracle/keeper/msg_server.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index 09f5b34d44..de1b2dcc48 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -281,5 +281,5 @@ func executeClaim( default: panic(fmt.Sprintf("receive unexpected package type %d", header.PackageType)) } - return + return crash, result } From 0811eb6a1cfd8c19e322a96585b4b216fe41f7d3 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 16 Jan 2023 10:20:47 +0800 Subject: [PATCH 47/50] fix unit tests --- x/oracle/keeper/msg_server_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x/oracle/keeper/msg_server_test.go b/x/oracle/keeper/msg_server_test.go index 1dd3fc3543..94be454885 100644 --- a/x/oracle/keeper/msg_server_test.go +++ b/x/oracle/keeper/msg_server_test.go @@ -15,15 +15,15 @@ import ( type DummyCrossChainApp struct{} -func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte, relayerFee *big.Int) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteSynPackage(ctx sdk.Context, header *sdk.CrossChainAppContext, payload []byte) sdk.ExecuteResult { return sdk.ExecuteResult{} } -func (ta *DummyCrossChainApp) ExecuteAckPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteAckPackage(ctx sdk.Context, header *sdk.CrossChainAppContext, payload []byte) sdk.ExecuteResult { return sdk.ExecuteResult{} } -func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, header *sdk.PackageHeader, payload []byte) sdk.ExecuteResult { +func (ta *DummyCrossChainApp) ExecuteFailAckPackage(ctx sdk.Context, header *sdk.CrossChainAppContext, payload []byte) sdk.ExecuteResult { return sdk.ExecuteResult{} } From 436689b1a170e8ddb8516b82d9ddb3f9a4ea6741 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 16 Jan 2023 11:07:49 +0800 Subject: [PATCH 48/50] update cross chain event --- proto/cosmos/crosschain/v1/event.proto | 2 +- x/crosschain/keeper/keeper.go | 3 +- x/crosschain/types/event.pb.go | 60 +++++++++++++------------- 3 files changed, 32 insertions(+), 33 deletions(-) diff --git a/proto/cosmos/crosschain/v1/event.proto b/proto/cosmos/crosschain/v1/event.proto index 78d3cfb898..a8529667b8 100644 --- a/proto/cosmos/crosschain/v1/event.proto +++ b/proto/cosmos/crosschain/v1/event.proto @@ -12,7 +12,7 @@ message EventCrossChain { uint64 sequence = 4; uint32 package_type = 5; uint64 timestamp = 6; - bytes package_load = 7; + string package_load = 7; string relayer_fee = 8; string ack_relayer_fee = 9; } diff --git a/x/crosschain/keeper/keeper.go b/x/crosschain/keeper/keeper.go index 14c422685c..aa60e74305 100644 --- a/x/crosschain/keeper/keeper.go +++ b/x/crosschain/keeper/keeper.go @@ -2,6 +2,7 @@ package keeper import ( "encoding/binary" + "encoding/hex" "fmt" "math/big" @@ -112,7 +113,7 @@ func (k Keeper) CreateRawIBCPackageWithFee(ctx sdk.Context, channelID sdk.Channe Sequence: sequence, PackageType: uint32(packageType), Timestamp: uint64(ctx.BlockTime().Unix()), - PackageLoad: packageLoad, + PackageLoad: hex.EncodeToString(packageLoad), RelayerFee: relayerFee.String(), AckRelayerFee: ackRelayerFee.String(), }) diff --git a/x/crosschain/types/event.pb.go b/x/crosschain/types/event.pb.go index e16e3c85b8..1fac3615d2 100644 --- a/x/crosschain/types/event.pb.go +++ b/x/crosschain/types/event.pb.go @@ -30,7 +30,7 @@ type EventCrossChain struct { Sequence uint64 `protobuf:"varint,4,opt,name=sequence,proto3" json:"sequence,omitempty"` PackageType uint32 `protobuf:"varint,5,opt,name=package_type,json=packageType,proto3" json:"package_type,omitempty"` Timestamp uint64 `protobuf:"varint,6,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - PackageLoad []byte `protobuf:"bytes,7,opt,name=package_load,json=packageLoad,proto3" json:"package_load,omitempty"` + PackageLoad string `protobuf:"bytes,7,opt,name=package_load,json=packageLoad,proto3" json:"package_load,omitempty"` RelayerFee string `protobuf:"bytes,8,opt,name=relayer_fee,json=relayerFee,proto3" json:"relayer_fee,omitempty"` AckRelayerFee string `protobuf:"bytes,9,opt,name=ack_relayer_fee,json=ackRelayerFee,proto3" json:"ack_relayer_fee,omitempty"` } @@ -110,11 +110,11 @@ func (m *EventCrossChain) GetTimestamp() uint64 { return 0 } -func (m *EventCrossChain) GetPackageLoad() []byte { +func (m *EventCrossChain) GetPackageLoad() string { if m != nil { return m.PackageLoad } - return nil + return "" } func (m *EventCrossChain) GetRelayerFee() string { @@ -138,28 +138,28 @@ func init() { func init() { proto.RegisterFile("cosmos/crosschain/v1/event.proto", fileDescriptor_2a5a3ba75f5dd2c3) } var fileDescriptor_2a5a3ba75f5dd2c3 = []byte{ - // 326 bytes of a gzipped FileDescriptorProto + // 323 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x4c, 0xd1, 0x4f, 0x4f, 0xfa, 0x30, 0x18, 0xc0, 0x71, 0xca, 0x8f, 0x1f, 0xb2, 0x07, 0x08, 0x49, 0xe3, 0x61, 0x31, 0x3a, 0x27, 0x07, - 0xb3, 0x8b, 0x5b, 0x88, 0xef, 0x40, 0xa2, 0x09, 0x89, 0xa7, 0xc5, 0x93, 0x97, 0xa5, 0xb4, 0x8f, - 0xb0, 0x8c, 0xad, 0x73, 0x2d, 0x44, 0xde, 0x85, 0xef, 0xc8, 0xab, 0x47, 0x8e, 0x1e, 0x0d, 0xbc, - 0x11, 0xd3, 0xf2, 0xf7, 0xb4, 0xec, 0xdb, 0x4f, 0x9f, 0xa4, 0x79, 0xc0, 0xe7, 0x52, 0xe5, 0x52, - 0x45, 0xbc, 0x92, 0x4a, 0xf1, 0x29, 0x4b, 0x8b, 0x68, 0x31, 0x88, 0x70, 0x81, 0x85, 0x0e, 0xcb, - 0x4a, 0x6a, 0x49, 0xcf, 0xb7, 0x22, 0x3c, 0x8a, 0x70, 0x31, 0xe8, 0x7f, 0xd5, 0xa1, 0xf7, 0x68, - 0xd4, 0xd0, 0xe4, 0xa1, 0xc9, 0xd4, 0x87, 0x8e, 0xaa, 0x78, 0x62, 0x4d, 0x92, 0x0a, 0x97, 0xf8, - 0x24, 0xe8, 0xc6, 0xa0, 0x2a, 0x6e, 0xcf, 0x47, 0x82, 0xf6, 0xa1, 0x2b, 0x50, 0xe9, 0x23, 0xa9, - 0x5b, 0xd2, 0x36, 0x71, 0x6f, 0xae, 0x00, 0xf8, 0x94, 0x15, 0x05, 0xce, 0x0c, 0xf8, 0x67, 0x81, - 0xb3, 0x2b, 0x23, 0x41, 0x2f, 0xa0, 0xa5, 0xf0, 0x7d, 0x8e, 0x05, 0x47, 0xb7, 0xe1, 0x93, 0xa0, - 0x11, 0x1f, 0xfe, 0xe9, 0x0d, 0x74, 0x4a, 0xc6, 0x33, 0x36, 0xc1, 0x44, 0x2f, 0x4b, 0x74, 0xff, - 0x6f, 0xa7, 0xef, 0xda, 0xcb, 0xb2, 0x44, 0x7a, 0x09, 0x8e, 0x4e, 0x73, 0x54, 0x9a, 0xe5, 0xa5, - 0xdb, 0xb4, 0xf7, 0x8f, 0xe1, 0x74, 0xc0, 0x4c, 0x32, 0xe1, 0x9e, 0xf9, 0x24, 0xe8, 0x1c, 0x06, - 0x3c, 0x4b, 0x26, 0xe8, 0x35, 0xb4, 0x2b, 0x9c, 0xb1, 0x25, 0x56, 0xc9, 0x1b, 0xa2, 0xdb, 0xf2, - 0x49, 0xe0, 0xc4, 0xb0, 0x4b, 0x4f, 0x88, 0xf4, 0x16, 0x7a, 0x8c, 0x67, 0xc9, 0x29, 0x72, 0x2c, - 0xea, 0x32, 0x9e, 0xc5, 0x07, 0xf7, 0x30, 0xfa, 0x5e, 0x7b, 0x64, 0xb5, 0xf6, 0xc8, 0xef, 0xda, - 0x23, 0x9f, 0x1b, 0xaf, 0xb6, 0xda, 0x78, 0xb5, 0x9f, 0x8d, 0x57, 0x7b, 0x8d, 0x26, 0xa9, 0x9e, - 0xce, 0xc7, 0x21, 0x97, 0x79, 0xb4, 0x5f, 0x8f, 0xfd, 0xdc, 0x29, 0x91, 0x45, 0x1f, 0xa7, 0xbb, - 0x32, 0xcf, 0x54, 0xe3, 0xa6, 0xdd, 0xd4, 0xfd, 0x5f, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3a, 0x57, - 0x60, 0xd9, 0xcd, 0x01, 0x00, 0x00, + 0xc3, 0xc5, 0x2d, 0xc4, 0x77, 0x20, 0xd1, 0x84, 0xc4, 0x13, 0xf1, 0xe4, 0x65, 0x29, 0xed, 0x23, + 0x2c, 0x63, 0xeb, 0x6c, 0x0b, 0x91, 0x77, 0xe1, 0x3b, 0xf2, 0xea, 0x91, 0xa3, 0x47, 0x03, 0x6f, + 0xc4, 0xb4, 0xfc, 0x3d, 0x2d, 0xfb, 0xf6, 0xd3, 0x27, 0x69, 0x1e, 0x08, 0xb9, 0xd4, 0xb9, 0xd4, + 0x31, 0x57, 0x52, 0x6b, 0x3e, 0x65, 0x69, 0x11, 0x2f, 0xfa, 0x31, 0x2e, 0xb0, 0x30, 0x51, 0xa9, + 0xa4, 0x91, 0xf4, 0x7c, 0x2b, 0xa2, 0xa3, 0x88, 0x16, 0xfd, 0xee, 0x57, 0x15, 0x3a, 0x8f, 0x56, + 0x0d, 0x6c, 0x1e, 0xd8, 0x4c, 0x43, 0x68, 0x69, 0xc5, 0x13, 0x67, 0x92, 0x54, 0xf8, 0x24, 0x24, + 0xbd, 0xf6, 0x08, 0xb4, 0xe2, 0xee, 0x7c, 0x28, 0x68, 0x17, 0xda, 0x02, 0xb5, 0x39, 0x92, 0xaa, + 0x23, 0x4d, 0x1b, 0xf7, 0xe6, 0x0a, 0x80, 0x4f, 0x59, 0x51, 0xe0, 0xcc, 0x82, 0x7f, 0x0e, 0x78, + 0xbb, 0x32, 0x14, 0xf4, 0x02, 0x1a, 0x1a, 0xdf, 0xe7, 0x58, 0x70, 0xf4, 0x6b, 0x21, 0xe9, 0xd5, + 0x46, 0x87, 0x7f, 0x7a, 0x03, 0xad, 0x92, 0xf1, 0x8c, 0x4d, 0x30, 0x31, 0xcb, 0x12, 0xfd, 0xff, + 0xdb, 0xe9, 0xbb, 0xf6, 0xb2, 0x2c, 0x91, 0x5e, 0x82, 0x67, 0xd2, 0x1c, 0xb5, 0x61, 0x79, 0xe9, + 0xd7, 0xdd, 0xfd, 0x63, 0x38, 0x1d, 0x30, 0x93, 0x4c, 0xf8, 0x67, 0x21, 0xe9, 0x79, 0x87, 0x01, + 0xcf, 0x92, 0x09, 0x7a, 0x0d, 0x4d, 0x85, 0x33, 0xb6, 0x44, 0x95, 0xbc, 0x21, 0xfa, 0x0d, 0x27, + 0x60, 0x97, 0x9e, 0x10, 0xe9, 0x2d, 0x74, 0x18, 0xcf, 0x92, 0x53, 0xe4, 0x39, 0xd4, 0x66, 0x3c, + 0x1b, 0x1d, 0xdc, 0xc3, 0xf0, 0x7b, 0x1d, 0x90, 0xd5, 0x3a, 0x20, 0xbf, 0xeb, 0x80, 0x7c, 0x6e, + 0x82, 0xca, 0x6a, 0x13, 0x54, 0x7e, 0x36, 0x41, 0xe5, 0x35, 0x9e, 0xa4, 0x66, 0x3a, 0x1f, 0x47, + 0x5c, 0xe6, 0xf1, 0x7e, 0x3d, 0xee, 0x73, 0xa7, 0x45, 0x16, 0x7f, 0x9c, 0xee, 0xca, 0x3e, 0x53, + 0x8f, 0xeb, 0x6e, 0x53, 0xf7, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0x93, 0x08, 0x3b, 0x98, 0xcd, + 0x01, 0x00, 0x00, } func (m *EventCrossChain) Marshal() (dAtA []byte, err error) { @@ -439,7 +439,7 @@ func (m *EventCrossChain) Unmarshal(dAtA []byte) error { if wireType != 2 { return fmt.Errorf("proto: wrong wireType = %d for field PackageLoad", wireType) } - var byteLen int + var stringLen uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowEvent @@ -449,25 +449,23 @@ func (m *EventCrossChain) Unmarshal(dAtA []byte) error { } b := dAtA[iNdEx] iNdEx++ - byteLen |= int(b&0x7F) << shift + stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } } - if byteLen < 0 { + intStringLen := int(stringLen) + if intStringLen < 0 { return ErrInvalidLengthEvent } - postIndex := iNdEx + byteLen + postIndex := iNdEx + intStringLen if postIndex < 0 { return ErrInvalidLengthEvent } if postIndex > l { return io.ErrUnexpectedEOF } - m.PackageLoad = append(m.PackageLoad[:0], dAtA[iNdEx:postIndex]...) - if m.PackageLoad == nil { - m.PackageLoad = []byte{} - } + m.PackageLoad = string(dAtA[iNdEx:postIndex]) iNdEx = postIndex case 8: if wireType != 2 { From 8008310b3fd93f2a1467e8729c0892964012452d Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 16 Jan 2023 15:22:52 +0800 Subject: [PATCH 49/50] fix unit tests --- x/oracle/keeper/keeper_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 6ef21a8bf3..7b2915fc51 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -153,7 +153,7 @@ func (s *TestSuite) TestKeeper_IsRelayerValid() { for i := range vals { pk := ed25519.GenPrivKey().PubKey() - vals[i] = newValidator(s.T(), sdk.ValAddress(pk.Address()), pk) + vals[i] = newValidator(s.T(), sdk.AccAddress(pk.Address()), pk) } val0Addr := vals[0].RelayerAddress @@ -260,13 +260,13 @@ func (s *TestSuite) TestKeeper_IsRelayerValid() { } // Creates a new validators and asserts the error check. -func newValidator(t *testing.T, operator sdk.ValAddress, pubKey cryptotypes.PubKey) stakingtypes.Validator { +func newValidator(t *testing.T, operator sdk.AccAddress, pubKey cryptotypes.PubKey) stakingtypes.Validator { v, err := stakingtypes.NewSimpleValidator(operator, pubKey, stakingtypes.Description{}) require.NoError(t, err) return v } -func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.ValAddress, []stakingtypes.Validator, []bls.SecretKey) { +func createValidators(t *testing.T, ctx sdk.Context, app *simapp.SimApp, powers []int64) ([]sdk.AccAddress, []sdk.AccAddress, []stakingtypes.Validator, []bls.SecretKey) { addrs := simapp.AddTestAddrsIncremental(app, ctx, 5, app.StakingKeeper.TokensFromConsensusPower(ctx, 300)) valAddrs := simapp.ConvertAddrsToValAddrs(addrs) pks := simapp.CreateTestPubKeys(5) From e0fa0c2a1f216d23de6f885ff9776521c2d0c8e5 Mon Sep 17 00:00:00 2001 From: yutianwu Date: Mon, 16 Jan 2023 16:59:45 +0800 Subject: [PATCH 50/50] increase oracle channel sequence when claim processed successfully --- x/oracle/keeper/msg_server.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/x/oracle/keeper/msg_server.go b/x/oracle/keeper/msg_server.go index de1b2dcc48..25373d5724 100644 --- a/x/oracle/keeper/msg_server.go +++ b/x/oracle/keeper/msg_server.go @@ -87,6 +87,8 @@ func (k msgServer) Claim(goCtx context.Context, req *types.MsgClaim) (*types.Msg return nil, err } + k.oracleKeeper.CrossChainKeeper.IncrReceiveSequence(ctx, types.RelayPackagesChannelId) + ctx.EventManager().EmitTypedEvents(events...) return &types.MsgClaimResponse{}, nil