From 1208482d7a7d642fd28978a66b9db445800b1d27 Mon Sep 17 00:00:00 2001 From: vishal Date: Fri, 15 Dec 2023 15:38:55 +0530 Subject: [PATCH 01/18] chore: upgraded app with paloma module to SDK v0.50 --- app/app.go | 43 +++++++++++----------- x/paloma/ante.go | 58 +++++++++++++++++------------- x/paloma/genesis.go | 7 ++-- x/paloma/keeper/keeper.go | 53 +++++++++++++++------------ x/paloma/keeper/msg_server.go | 7 ++-- x/paloma/keeper/params.go | 9 +++-- x/paloma/module.go | 32 ++++++++++++----- x/paloma/module_simulation.go | 3 +- x/paloma/types/errors.go | 2 +- x/paloma/types/expected_keepers.go | 15 ++++---- 10 files changed, 132 insertions(+), 97 deletions(-) diff --git a/app/app.go b/app/app.go index 417aad40..a9dbcc3c 100644 --- a/app/app.go +++ b/app/app.go @@ -139,9 +139,9 @@ import ( // gravityclient "github.com/palomachain/paloma/x/gravity/client" // gravitymodulekeeper "github.com/palomachain/paloma/x/gravity/keeper" // gravitymoduletypes "github.com/palomachain/paloma/x/gravity/types" - // palomamodule "github.com/palomachain/paloma/x/paloma" - // palomamodulekeeper "github.com/palomachain/paloma/x/paloma/keeper" - // palomamoduletypes "github.com/palomachain/paloma/x/paloma/types" + palomamodule "github.com/palomachain/paloma/x/paloma" + palomamodulekeeper "github.com/palomachain/paloma/x/paloma/keeper" + palomamoduletypes "github.com/palomachain/paloma/x/paloma/types" schedulermodule "github.com/palomachain/paloma/x/scheduler" schedulermodulekeeper "github.com/palomachain/paloma/x/scheduler/keeper" schedulermoduletypes "github.com/palomachain/paloma/x/scheduler/types" @@ -249,7 +249,7 @@ type App struct { SchedulerKeeper schedulermodulekeeper.Keeper ConsensusKeeper consensusmodulekeeper.Keeper // ValsetKeeper valsetmodulekeeper.Keeper - // PalomaKeeper palomamodulekeeper.Keeper + PalomaKeeper palomamodulekeeper.Keeper // TreasuryKeeper treasurymodulekeeper.Keeper EvmKeeper evmmodulekeeper.Keeper // GravityKeeper gravitymodulekeeper.Keeper @@ -343,7 +343,7 @@ func New( evmmoduletypes.MemStoreKey, schedulermoduletypes.MemStoreKey, // treasurymoduletypes.MemStoreKey, - // palomamoduletypes.MemStoreKey, + palomamoduletypes.MemStoreKey, ) app := &App{ @@ -573,19 +573,18 @@ func New( // gravitymodulekeeper.NewGravityStoreGetter(keys[gravitymoduletypes.StoreKey]), // ) - // app.PalomaKeeper = *palomamodulekeeper.NewKeeper( - // appCodec, - // keys[palomamoduletypes.StoreKey], - // memKeys[palomamoduletypes.MemStoreKey], - // app.GetSubspace(palomamoduletypes.ModuleName), - // semverVersion, - // app.ValsetKeeper, - // app.PalomaKeeper.Upgrade, - // ) + app.PalomaKeeper = *palomamodulekeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[palomamoduletypes.StoreKey]), + app.GetSubspace(palomamoduletypes.ModuleName), + semverVersion, + nil, //app.ValsetKeeper (TODO), + app.PalomaKeeper.Upgrade, + ) - // app.PalomaKeeper.ExternalChains = []palomamoduletypes.ExternalChainSupporterKeeper{ - // app.EvmKeeper, - // } + app.PalomaKeeper.ExternalChains = []palomamoduletypes.ExternalChainSupporterKeeper{ + app.EvmKeeper, + } // Create evidence Keeper for to register the IBC light client misbehaviour evidence route evidenceKeeper := evidencekeeper.NewKeeper( @@ -737,7 +736,7 @@ func New( consensusModule := consensusmodule.NewAppModule(appCodec, app.ConsensusKeeper, app.AccountKeeper, app.BankKeeper) // valsetModule := valsetmodule.NewAppModule(appCodec, app.ValsetKeeper, app.AccountKeeper, app.BankKeeper) schedulerModule := schedulermodule.NewAppModule(appCodec, app.SchedulerKeeper, app.AccountKeeper, app.BankKeeper) - // palomaModule := palomamodule.NewAppModule(appCodec, app.PalomaKeeper, app.AccountKeeper, app.BankKeeper) + palomaModule := palomamodule.NewAppModule(appCodec, app.PalomaKeeper, app.AccountKeeper, app.BankKeeper) // gravityModule := gravitymodule.NewAppModule(appCodec, app.GravityKeeper, app.BankKeeper) // treasuryModule := treasurymodule.NewAppModule(appCodec, app.TreasuryKeeper, app.AccountKeeper, app.BankKeeper) app.ModuleManager = module.NewManager( @@ -766,7 +765,7 @@ func New( // valsetModule, evmModule, // gravityModule, - // palomaModule, + palomaModule, // treasuryModule, wasm.NewAppModule(appCodec, &app.wasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasm.ModuleName)), ibc.NewAppModule(app.IBCKeeper), @@ -811,7 +810,7 @@ func New( vestingtypes.ModuleName, genutiltypes.ModuleName, // valsetmoduletypes.ModuleName, - // palomamoduletypes.ModuleName, + palomamoduletypes.ModuleName, evmmoduletypes.ModuleName, wasmtypes.ModuleName, // gravitymoduletypes.ModuleName, @@ -843,7 +842,7 @@ func New( vestingtypes.ModuleName, genutiltypes.ModuleName, // valsetmoduletypes.ModuleName, - // palomamoduletypes.ModuleName, + palomamoduletypes.ModuleName, evmmoduletypes.ModuleName, wasmtypes.ModuleName, // evmmoduletypes.ModuleName, @@ -881,7 +880,7 @@ func New( schedulermoduletypes.ModuleName, consensusmoduletypes.ModuleName, // valsetmoduletypes.ModuleName, - // palomamoduletypes.ModuleName, + palomamoduletypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, icatypes.ModuleName, diff --git a/x/paloma/ante.go b/x/paloma/ante.go index 00021fd0..aa9f640b 100644 --- a/x/paloma/ante.go +++ b/x/paloma/ante.go @@ -1,20 +1,23 @@ package paloma import ( + "context" "fmt" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + "cosmossdk.io/x/feegrant" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" "github.com/gogo/protobuf/proto" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/util/libmeta" "github.com/palomachain/paloma/x/paloma/types" vtypes "github.com/palomachain/paloma/x/valset/types" ) -func logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +func logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return liblog.FromSDKLogger(sdkCtx.Logger()).With("module", fmt.Sprintf("x/%s", types.ModuleName)) } // HandlerDecorator is an ante decorator wrapper for an ante handler @@ -28,12 +31,14 @@ func NewAnteHandlerDecorator(handler sdk.AnteHandler) HandlerDecorator { } // AnteHandle wraps the next AnteHandler to perform custom pre- and post-processing -func (decorator HandlerDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - if newCtx, err = decorator.handler(ctx, tx, simulate); err != nil { +func (decorator HandlerDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx context.Context, err error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + + if newCtx, err = decorator.handler(sdkCtx, tx, simulate); err != nil { return newCtx, err } - return next(newCtx, tx, simulate) + return next(sdkCtx, tx, simulate) } // LogMsgDecorator logs all messages in blocks @@ -47,22 +52,24 @@ func NewLogMsgDecorator(cdc codec.Codec) LogMsgDecorator { } // AnteHandle logs all messages in blocks -func (d LogMsgDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - if simulate || ctx.IsCheckTx() { - return next(ctx, tx, simulate) +func (d LogMsgDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (context.Context, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + + if simulate || sdkCtx.IsCheckTx() { + return next(sdkCtx, tx, simulate) } msgs := tx.GetMsgs() for _, msg := range msgs { - logger(ctx).Debug(fmt.Sprintf("received message of type %s in block %d: %s", + liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("received message of type %s in block %d: %s", proto.MessageName(msg), - ctx.BlockHeight(), + sdkCtx.BlockHeight(), string(d.cdc.MustMarshalJSON(msg)), )) } - return next(ctx, tx, simulate) + return next(sdkCtx, tx, simulate) } // VerifyAuthorisedSignatureDecorator verifies that the message is signed by at least one signature that has @@ -77,31 +84,32 @@ func NewVerifyAuthorisedSignatureDecorator(fk types.FeegrantKeeper) VerifyAuthor // AnteHandle verifies that the message is signed by at least one signature that has // active fee grant from the creator address, IF the message contains metadata. -func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { +func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (context.Context, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) if simulate { - return next(ctx, tx, simulate) + return next(sdkCtx, tx, simulate) } for _, msg := range tx.GetMsgs() { m, ok := msg.(libmeta.MsgWithMetadata[vtypes.MsgMetadata]) if !ok { - logger(ctx).Debug(fmt.Sprintf("msg %s does not contain metadata. skipping ownership verification...", proto.MessageName(msg))) + liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("msg %s does not contain metadata. skipping ownership verification...", proto.MessageName(msg))) continue } creator := m.GetMetadata().GetCreator() - signers := msg.GetSigners() + signers := m.GetMetadata().GetSigners() signedByCreator := func() bool { for _, v := range signers { - if v.String() == creator { + if v == creator { return true } } return false }() if signedByCreator { - logger(ctx).Debug(fmt.Sprintf("msg %s was signed by creator.", proto.MessageName(msg))) + liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("msg %s was signed by creator.", proto.MessageName(msg))) continue } @@ -112,21 +120,21 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T return ctx, fmt.Errorf("failed to verify message signature authorisation: %w", err) } - logger(ctx).Debug(fmt.Sprintf("got %d allowances from granter %s", len(grants.GetAllowances()), creator)) + liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("got %d allowances from granter %s", len(grants.GetAllowances()), creator)) grantsLkUp := map[string]feegrant.Grant{} for _, v := range grants.GetAllowances() { if v == nil { continue } - logger(ctx).Debug("found allowance", "granter", v.GetGranter(), "grantee", v.GetGrantee()) + liblog.FromSDKLogger(logger(ctx)).WithFields("granter", v.GetGranter(), "grantee", v.GetGrantee()).Debug("found allowance") grantsLkUp[v.GetGrantee()] = *v } grantees := make([]string, 0, len(signers)) for _, signer := range signers { - if v, found := grantsLkUp[signer.String()]; found { - logger(ctx).Debug("found granted signature", "signature", v.Grantee) + if v, found := grantsLkUp[signer]; found { + liblog.FromSDKLogger(logger(ctx)).WithFields( "signature", v.Grantee).Debug("found granted signature") grantees = append(grantees, v.Grantee) } } @@ -135,8 +143,8 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T return ctx, fmt.Errorf("no signature from granted address found for message %s", proto.MessageName(msg)) } - logger(ctx).Debug(fmt.Sprintf("found total of %d signatures from granted addresses for message %s", len(grantees), proto.MessageName(msg))) + liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("found total of %d signatures from granted addresses for message %s", len(grantees), proto.MessageName(msg))) } - return next(ctx, tx, simulate) + return next(sdkCtx, tx, simulate) } diff --git a/x/paloma/genesis.go b/x/paloma/genesis.go index eb826258..445a96f2 100644 --- a/x/paloma/genesis.go +++ b/x/paloma/genesis.go @@ -1,19 +1,20 @@ package paloma import ( - sdk "github.com/cosmos/cosmos-sdk/types" + "context" + "github.com/palomachain/paloma/x/paloma/keeper" "github.com/palomachain/paloma/x/paloma/types" ) // InitGenesis initializes the capability module's state from a provided genesis // state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { +func InitGenesis(ctx context.Context, k keeper.Keeper, genState types.GenesisState) { k.SetParams(ctx, genState.Params) } // ExportGenesis returns the capability module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { +func ExportGenesis(ctx context.Context, k keeper.Keeper) *types.GenesisState { genesis := types.DefaultGenesis() genesis.Params = k.GetParams(ctx) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 4729300e..da97020f 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -1,38 +1,39 @@ package keeper import ( + "context" "fmt" "sort" "strings" + "cosmossdk.io/core/address" + cosmosstore "cosmossdk.io/core/store" + "cosmossdk.io/log" "github.com/VolumeFi/whoops" - "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/paloma/types" "golang.org/x/mod/semver" ) type ( Keeper struct { - cdc codec.BinaryCodec - storeKey storetypes.StoreKey - memKey storetypes.StoreKey - paramstore paramtypes.Subspace - Valset types.ValsetKeeper - Upgrade types.UpgradeKeeper - AppVersion string - + cdc codec.BinaryCodec + storeKey cosmosstore.KVStoreService + paramstore paramtypes.Subspace + Valset types.ValsetKeeper + Upgrade types.UpgradeKeeper + AppVersion string + addressCodec address.Codec ExternalChains []types.ExternalChainSupporterKeeper } ) func NewKeeper( cdc codec.BinaryCodec, - storeKey, - memKey storetypes.StoreKey, + storeKey cosmosstore.KVStoreService, ps paramtypes.Subspace, appVersion string, valset types.ValsetKeeper, @@ -53,7 +54,6 @@ func NewKeeper( return &Keeper{ cdc: cdc, storeKey: storeKey, - memKey: memKey, paramstore: ps, Valset: valset, Upgrade: upgrade, @@ -62,27 +62,32 @@ func NewKeeper( } } -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +func (k Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return liblog.FromSDKLogger(sdkCtx.Logger()).With("module", fmt.Sprintf("x/%s", types.ModuleName)) } -func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx sdk.Context) error { - k.Logger(ctx).Info("start jailing validators with invalid external chain infos") +func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) error { + liblog.FromSDKLogger(k.Logger(ctx)).Info("start jailing validators with invalid external chain infos") vals := k.Valset.GetUnjailedValidators(ctx) - + sdkCtx := sdk.UnwrapSDKContext(ctx) // making a map of chain types and their external chains type mapkey [2]string mmap := make(map[mapkey]struct{}) for _, supported := range k.ExternalChains { chainType := supported.XChainType() - for _, cri := range supported.XChainReferenceIDs(ctx) { + for _, cri := range supported.XChainReferenceIDs(sdkCtx) { mmap[mapkey{string(chainType), string(cri)}] = struct{}{} } } var g whoops.Group for _, val := range vals { - exts, err := k.Valset.GetValidatorChainInfos(ctx, val.GetOperator()) + bz, err := k.addressCodec.StringToBytes(val.GetOperator()) + if err != nil { + return err + } + exts, err := k.Valset.GetValidatorChainInfos(ctx, bz) if err != nil { g.Add(err) continue @@ -103,8 +108,12 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx sdk.Context) err sort.Strings(notSupported) + bz, err = k.addressCodec.StringToBytes(val.GetOperator()) + if err != nil { + return err + } if len(notSupported) > 0 { - g.Add(k.Valset.Jail(ctx, val.GetOperator(), fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) + g.Add(k.Valset.Jail(ctx, bz, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) } } @@ -113,7 +122,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx sdk.Context) err // CheckChainVersion will exit if the app version and the government proposed // versions do not match. -func (k Keeper) CheckChainVersion(ctx sdk.Context) { +func (k Keeper) CheckChainVersion(ctx context.Context) { // app needs to be in the [major].[minor] space, // but needs to be running at least [major].[minor].[patch] govVer, govHeight := k.Upgrade.GetLastCompletedUpgrade(ctx) diff --git a/x/paloma/keeper/msg_server.go b/x/paloma/keeper/msg_server.go index 45e9ba76..b17a9480 100644 --- a/x/paloma/keeper/msg_server.go +++ b/x/paloma/keeper/msg_server.go @@ -5,6 +5,7 @@ import ( "os" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/paloma/types" ) @@ -38,11 +39,11 @@ func (k msgServer) AddStatusUpdate(goCtx context.Context, msg *types.MsgAddStatu var logFn func(string, ...interface{}) switch msg.Level { case types.MsgAddStatusUpdate_LEVEL_DEBUG: - logFn = k.Logger(ctx).Debug + logFn = liblog.FromSDKLogger(k.Logger(ctx)).Debug case types.MsgAddStatusUpdate_LEVEL_INFO: - logFn = k.Logger(ctx).Info + logFn = liblog.FromSDKLogger(k.Logger(ctx)).Info case types.MsgAddStatusUpdate_LEVEL_ERROR: - logFn = k.Logger(ctx).Error + logFn = liblog.FromSDKLogger(k.Logger(ctx)).Error } logFn(status, diff --git a/x/paloma/keeper/params.go b/x/paloma/keeper/params.go index 2b45a020..2160aae6 100644 --- a/x/paloma/keeper/params.go +++ b/x/paloma/keeper/params.go @@ -1,16 +1,19 @@ package keeper import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/paloma/types" ) // GetParams get all parameters as types.Params -func (k Keeper) GetParams(ctx sdk.Context) types.Params { +func (k Keeper) GetParams(ctx context.Context) types.Params { return types.NewParams() } // SetParams set the params -func (k Keeper) SetParams(ctx sdk.Context, params types.Params) { - k.paramstore.SetParamSet(ctx, ¶ms) +func (k Keeper) SetParams(ctx context.Context, params types.Params) { + sdkctx := sdk.UnwrapSDKContext(ctx) + k.paramstore.SetParamSet(sdkctx, ¶ms) } diff --git a/x/paloma/module.go b/x/paloma/module.go index 220b6833..aee4f396 100644 --- a/x/paloma/module.go +++ b/x/paloma/module.go @@ -1,9 +1,11 @@ package paloma import ( + "context" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -12,6 +14,7 @@ import ( "github.com/cosmos/cosmos-sdk/types/module" "github.com/gorilla/mux" "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/paloma/client/cli" "github.com/palomachain/paloma/x/paloma/keeper" "github.com/palomachain/paloma/x/paloma/types" @@ -19,14 +22,25 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.HasServices = AppModule{} + _ module.HasInvariants = AppModule{} + _ module.HasABCIGenesis = AppModule{} + _ module.HasConsensusVersion = AppModule{} + _ module.HasName = AppModule{} + + _ appmodule.HasEndBlocker = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} + _ appmodule.AppModule = AppModule{} ) // ---------------------------------------------------------------------------- // AppModuleBasic // ---------------------------------------------------------------------------- +func (m AppModule) IsOnePerModuleType() {} +func (m AppModule) IsAppModule() {} + // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { cdc codec.BinaryCodec @@ -153,18 +167,20 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw func (AppModule) ConsensusVersion() uint64 { return 1 } // BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) { +func (am AppModule) BeginBlock(ctx context.Context) error { am.keeper.CheckChainVersion(ctx) + return nil } // EndBlock executes all ABCI EndBlock logic respective to the capability module. It // returns no validator updates. -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - if ctx.BlockHeight()%303 == 0 { - err := am.keeper.JailValidatorsWithMissingExternalChainInfos(ctx) +func (am AppModule) EndBlock(ctx context.Context) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + if sdkCtx.BlockHeight()%303 == 0 { + err := am.keeper.JailValidatorsWithMissingExternalChainInfos(sdkCtx) if err != nil { - am.keeper.Logger(ctx).Error("wrror jailing validators with missing external chain infos", "err", err) + liblog.FromSDKLogger(am.keeper.Logger(sdkCtx)).WithError(err).Error("wrror jailing validators with missing external chain infos") } } - return []abci.ValidatorUpdate{} + return nil } diff --git a/x/paloma/module_simulation.go b/x/paloma/module_simulation.go index 5cb5e0d1..58061f28 100644 --- a/x/paloma/module_simulation.go +++ b/x/paloma/module_simulation.go @@ -2,7 +2,6 @@ package paloma import ( "github.com/cosmos/cosmos-sdk/baseapp" - 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/simulation" @@ -37,7 +36,7 @@ func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedP } // RegisterStoreDecoder registers a decoder -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { diff --git a/x/paloma/types/errors.go b/x/paloma/types/errors.go index 4c1992d0..3a8feb15 100644 --- a/x/paloma/types/errors.go +++ b/x/paloma/types/errors.go @@ -3,7 +3,7 @@ package types // DONTCOVER import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" ) // x/paloma module sentinel errors diff --git a/x/paloma/types/expected_keepers.go b/x/paloma/types/expected_keepers.go index a2e1dcda..c391ed3e 100644 --- a/x/paloma/types/expected_keepers.go +++ b/x/paloma/types/expected_keepers.go @@ -3,9 +3,8 @@ package types import ( context "context" + "cosmossdk.io/x/feegrant" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" xchain "github.com/palomachain/paloma/internal/x-chain" valsettypes "github.com/palomachain/paloma/x/valset/types" @@ -13,20 +12,20 @@ import ( // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI // Methods imported from account should be defined here } // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins // Methods imported from bank should be defined here } type ValsetKeeper interface { - GetUnjailedValidators(ctx sdk.Context) []stakingtypes.ValidatorI - Jail(ctx sdk.Context, valAddr sdk.ValAddress, reason string) error - GetValidatorChainInfos(ctx sdk.Context, valAddr sdk.ValAddress) ([]*valsettypes.ExternalChainInfo, error) + GetUnjailedValidators(ctx context.Context) []stakingtypes.ValidatorI + Jail(ctx context.Context, valAddr sdk.ValAddress, reason string) error + GetValidatorChainInfos(ctx context.Context, valAddr sdk.ValAddress) ([]*valsettypes.ExternalChainInfo, error) } type ExternalChainSupporterKeeper interface { @@ -34,7 +33,7 @@ type ExternalChainSupporterKeeper interface { } type UpgradeKeeper interface { - GetLastCompletedUpgrade(ctx sdk.Context) (string, int64) + GetLastCompletedUpgrade(ctx context.Context) (string, int64) } type FeegrantKeeper interface { From 44f60931a2dae4143e5274f9abd8b39f88caf8b0 Mon Sep 17 00:00:00 2001 From: ruthishvitwit Date: Tue, 19 Dec 2023 10:15:48 +0530 Subject: [PATCH 02/18] fix: resolved merge conflicts with v0.50.0-upgrade branch --- Makefile | 2 +- app/app.go | 204 +++++++++++------- app/app_setup.go | 2 - app/simulation_test.go | 3 - cmd/palomad/root.go | 2 + go.mod | 136 +++++++----- go.sum | 41 ++++ .../paloma/gravity/attestation.proto | 2 +- .../palomachain/paloma/treasury/params.proto | 4 +- testutil/keeper/valset.go | 4 +- util/keeper/address.go | 8 + x/evm/types/tx.pb.go | 63 +++--- x/gravity/abci.go | 18 +- x/gravity/abci_test.go | 11 +- x/gravity/client/cli/tx.go | 2 +- x/gravity/handler.go | 20 +- x/gravity/handler_test.go | 5 +- x/gravity/keeper/attestation.go | 96 +++++---- x/gravity/keeper/attestation_handler.go | 69 +++--- x/gravity/keeper/attestation_test.go | 5 +- x/gravity/keeper/batch.go | 50 +++-- x/gravity/keeper/batch_test.go | 49 ++--- x/gravity/keeper/cosmos-originated.go | 22 +- x/gravity/keeper/evidence.go | 17 +- x/gravity/keeper/evidence_test.go | 8 +- x/gravity/keeper/genesis.go | 7 +- x/gravity/keeper/genesis_test.go | 5 +- x/gravity/keeper/grpc_query.go | 6 +- .../keeper/grpc_query_integration_test.go | 17 +- x/gravity/keeper/grpc_query_test.go | 35 +-- x/gravity/keeper/hooks.go | 25 ++- x/gravity/keeper/invariants.go | 19 +- x/gravity/keeper/invariants_test.go | 26 ++- x/gravity/keeper/keeper.go | 72 ++++--- x/gravity/keeper/keeper_batch.go | 19 +- x/gravity/keeper/keeper_delegate_key.go | 18 +- x/gravity/keeper/keeper_test.go | 6 +- x/gravity/keeper/msg_server.go | 34 +-- x/gravity/keeper/pool.go | 43 ++-- x/gravity/keeper/pool_test.go | 52 ++--- x/gravity/keeper/test_common.go | 114 +++++----- x/gravity/module.go | 33 ++- x/gravity/types/attestation.go | 2 +- x/gravity/types/attestation.pb.go | 90 ++++---- x/gravity/types/batch_test.go | 3 +- x/gravity/types/ethereum.go | 14 +- x/gravity/types/expected_keepers.go | 77 ++++--- x/gravity/types/genesis.go | 22 +- x/gravity/types/genesis_test.go | 10 +- x/gravity/types/key_test.go | 4 +- x/gravity/types/msgs.go | 5 +- x/gravity/types/msgs_test.go | 3 +- x/gravity/types/test_utils.go | 5 +- x/gravity/types/validation.go | 2 +- x/treasury/genesis.go | 19 +- x/treasury/keeper/grpc_query_fees_test.go | 2 +- x/treasury/keeper/keeper.go | 23 +- x/treasury/keeper/keeper_test.go | 2 +- x/treasury/module.go | 23 +- x/treasury/module_simulation.go | 3 +- x/treasury/types/errors.go | 2 +- x/treasury/types/expected_keepers.go | 27 +-- x/treasury/types/mocks/TreasuryStore.go | 28 +-- x/treasury/types/params.go | 7 - x/treasury/types/params.pb.go | 21 +- x/treasury/types/store.go | 17 +- .../keeper/grpc_query_get_alive_pigeons.go | 10 +- ...uery_get_latest_published_snapshot_test.go | 11 +- .../grpc_query_get_validator_jail_reason.go | 6 +- x/valset/keeper/grpc_query_params_test.go | 2 +- x/valset/keeper/keep_alive.go | 81 ++++--- x/valset/keeper/keep_alive_test.go | 4 +- x/valset/keeper/keeper.go | 173 ++++++++------- x/valset/keeper/keeper_integration_test.go | 22 +- x/valset/keeper/keeper_test.go | 110 +++++----- x/valset/keeper/setup_test.go | 28 +-- x/valset/module.go | 38 ++-- x/valset/module_simulation.go | 6 +- x/valset/types/errors.go | 2 +- x/valset/types/expected_keepers.go | 19 +- x/valset/types/mocks/EvmKeeper.go | 26 ++- x/valset/types/mocks/StakingKeeper.go | 91 ++++++-- x/valset/types/mocks/ValidatorI.go | 117 ++++++++-- 83 files changed, 1510 insertions(+), 1021 deletions(-) create mode 100644 util/keeper/address.go diff --git a/Makefile b/Makefile index 0111bb37..033d64e6 100644 --- a/Makefile +++ b/Makefile @@ -143,4 +143,4 @@ proto-update-deps: @echo "Updating Protobuf dependencies" $(DOCKER) run --rm -v $(CURDIR)/proto:/workspace --workdir /workspace $(protoImageName) buf mod update -.PHONY: proto-all proto-gen proto-format proto-lint proto-check-breaking proto-update-deps +.PHONY: proto-all proto-gen proto-format proto-lint proto-check-breaking proto-update-deps \ No newline at end of file diff --git a/app/app.go b/app/app.go index a9dbcc3c..d1a194f3 100644 --- a/app/app.go +++ b/app/app.go @@ -123,37 +123,38 @@ import ( ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" + ibcclient "github.com/cosmos/ibc-go/v8/modules/core/02-client" + ibcclienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types" palomamempool "github.com/palomachain/paloma/app/mempool" - appparams "github.com/palomachain/paloma/app/params" consensusmodule "github.com/palomachain/paloma/x/consensus" consensusmodulekeeper "github.com/palomachain/paloma/x/consensus/keeper" consensusmoduletypes "github.com/palomachain/paloma/x/consensus/types" + gravitymodule "github.com/palomachain/paloma/x/gravity" + gravityclient "github.com/palomachain/paloma/x/gravity/client" + gravitymodulekeeper "github.com/palomachain/paloma/x/gravity/keeper" + gravitymoduletypes "github.com/palomachain/paloma/x/gravity/types" + "github.com/palomachain/paloma/x/evm" evmclient "github.com/palomachain/paloma/x/evm/client" evmmodulekeeper "github.com/palomachain/paloma/x/evm/keeper" evmmoduletypes "github.com/palomachain/paloma/x/evm/types" - // gravitymodule "github.com/palomachain/paloma/x/gravity" - // gravityclient "github.com/palomachain/paloma/x/gravity/client" - // gravitymodulekeeper "github.com/palomachain/paloma/x/gravity/keeper" - // gravitymoduletypes "github.com/palomachain/paloma/x/gravity/types" - palomamodule "github.com/palomachain/paloma/x/paloma" palomamodulekeeper "github.com/palomachain/paloma/x/paloma/keeper" palomamoduletypes "github.com/palomachain/paloma/x/paloma/types" schedulermodule "github.com/palomachain/paloma/x/scheduler" schedulermodulekeeper "github.com/palomachain/paloma/x/scheduler/keeper" schedulermoduletypes "github.com/palomachain/paloma/x/scheduler/types" - // treasurymodule "github.com/palomachain/paloma/x/treasury" - // treasuryclient "github.com/palomachain/paloma/x/treasury/client" - // treasurymodulekeeper "github.com/palomachain/paloma/x/treasury/keeper" - // treasurymoduletypes "github.com/palomachain/paloma/x/treasury/types" + treasurymodule "github.com/palomachain/paloma/x/treasury" + treasuryclient "github.com/palomachain/paloma/x/treasury/client" + treasurymodulekeeper "github.com/palomachain/paloma/x/treasury/keeper" + treasurymoduletypes "github.com/palomachain/paloma/x/treasury/types" - // valsetmodule "github.com/palomachain/paloma/x/valset" - // valsetmodulekeeper "github.com/palomachain/paloma/x/valset/keeper" - // valsetmoduletypes "github.com/palomachain/paloma/x/valset/types" + valsetmodule "github.com/palomachain/paloma/x/valset" + valsetmodulekeeper "github.com/palomachain/paloma/x/valset/keeper" + valsetmoduletypes "github.com/palomachain/paloma/x/valset/types" "github.com/spf13/cast" ) @@ -168,7 +169,10 @@ const ( func getGovProposalHandlers() []govclient.ProposalHandler { return []govclient.ProposalHandler{ paramsclient.ProposalHandler, + gravityclient.ProposalHandler, + // treasuryclient.ProposalHandler, evmclient.ProposalHandler, + treasuryclient.ProposalHandler, } } @@ -176,6 +180,40 @@ var ( // DefaultNodeHome default home directories for the application daemon DefaultNodeHome string + // ModuleBasics defines the module BasicManager is in charge of setting up basic, + // non-dependant module elements, such as codec registration + // and genesis verification. + ModuleBasics = module.NewBasicManager( + auth.AppModuleBasic{}, + genutil.NewAppModuleBasic(genutiltypes.DefaultMessageValidator), + bank.AppModule{}, + capability.AppModuleBasic{}, + staking.AppModule{}, + mint.AppModule{}, + distr.AppModuleBasic{}, + gov.AppModule{AppModuleBasic: gov.NewAppModuleBasic(getGovProposalHandlers())}, + params.AppModuleBasic{}, + crisis.AppModule{}, + slashing.AppModule{}, + feegrantmodule.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + vesting.AppModuleBasic{}, + schedulermodule.AppModuleBasic{}, + consensusmodule.AppModuleBasic{}, + // valsetmodule.AppModuleBasic{}, + wasm.AppModuleBasic{}, + evm.AppModuleBasic{}, + gravitymodule.AppModuleBasic{}, + // palomamodule.AppModuleBasic{}, + // treasurymodule.AppModuleBasic{}, + consensus.AppModuleBasic{}, + transfer.AppModuleBasic{}, + ibc.AppModuleBasic{}, + ica.AppModuleBasic{}, + ibcfee.AppModuleBasic{}, + ) + // module account permissions maccPerms = map[string][]string{ authtypes.FeeCollectorName: nil, @@ -184,10 +222,12 @@ var ( stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, govtypes.ModuleName: {authtypes.Burner}, + gravitymoduletypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, ibcfeetypes.ModuleName: nil, icatypes.ModuleName: nil, - evmmoduletypes.ModuleName: {authtypes.Burner, authtypes.Minter}, + wasmtypes.ModuleName: {authtypes.Burner}, + treasurymoduletypes.ModuleName: {authtypes.Burner, authtypes.Minter}, } ) @@ -248,12 +288,12 @@ type App struct { SchedulerKeeper schedulermodulekeeper.Keeper ConsensusKeeper consensusmodulekeeper.Keeper - // ValsetKeeper valsetmodulekeeper.Keeper - PalomaKeeper palomamodulekeeper.Keeper - // TreasuryKeeper treasurymodulekeeper.Keeper - EvmKeeper evmmodulekeeper.Keeper - // GravityKeeper gravitymodulekeeper.Keeper - wasmKeeper wasmkeeper.Keeper + ValsetKeeper valsetmodulekeeper.Keeper + PalomaKeeper palomamodulekeeper.Keeper + TreasuryKeeper treasurymodulekeeper.Keeper + EvmKeeper evmmodulekeeper.Keeper + GravityKeeper gravitymodulekeeper.Keeper + wasmKeeper wasmkeeper.Keeper // ModuleManager is the module manager ModuleManager *module.Manager @@ -271,7 +311,6 @@ func New( db dbm.DB, traceStore io.Writer, loadLatest bool, - encodingCfg appparams.EncodingConfig, appOpts servertypes.AppOptions, baseAppOptions ...func(*baseapp.BaseApp), ) *App { @@ -327,22 +366,22 @@ func New( schedulermoduletypes.StoreKey, consensusmoduletypes.StoreKey, // valsetmoduletypes.StoreKey, + treasurymoduletypes.StoreKey, + valsetmoduletypes.StoreKey, // treasurymoduletypes.StoreKey, evmmoduletypes.StoreKey, - wasmtypes.StoreKey, - // evmmoduletypes.StoreKey, - // gravitymoduletypes.StoreKey, + gravitymoduletypes.StoreKey, consensusparamtypes.StoreKey, crisistypes.StoreKey, ) tkeys := storetypes.NewTransientStoreKeys(paramstypes.TStoreKey) memKeys := storetypes.NewMemoryStoreKeys( capabilitytypes.MemStoreKey, - // valsetmoduletypes.MemStoreKey, + valsetmoduletypes.MemStoreKey, consensusmoduletypes.MemStoreKey, evmmoduletypes.MemStoreKey, schedulermoduletypes.MemStoreKey, - // treasurymoduletypes.MemStoreKey, + treasurymoduletypes.MemStoreKey, palomamoduletypes.MemStoreKey, ) @@ -528,15 +567,14 @@ func New( stakingtypes.NewMultiStakingHooks(app.DistrKeeper.Hooks(), app.SlashingKeeper.Hooks()), ) - // app.ValsetKeeper = *valsetmodulekeeper.NewKeeper( - // appCodec, - // keys[valsetmoduletypes.StoreKey], - // memKeys[valsetmoduletypes.MemStoreKey], - // app.GetSubspace(valsetmoduletypes.ModuleName), - // app.StakingKeeper, - // minimumPigeonVersion, - // sdk.DefaultPowerReduction, - // ) + app.ValsetKeeper = *valsetmodulekeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[valsetmoduletypes.StoreKey]), + app.GetSubspace(valsetmoduletypes.ModuleName), + app.StakingKeeper, + minimumPigeonVersion, + sdk.DefaultPowerReduction, + ) consensusRegistry := consensusmodulekeeper.NewRegistry() @@ -555,23 +593,23 @@ func New( nil, //TODO authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - // app.ValsetKeeper.SnapshotListeners = []valsetmoduletypes.OnSnapshotBuiltListener{ - // app.EvmKeeper, - // } - // app.ValsetKeeper.EvmKeeper = app.EvmKeeper - - // app.GravityKeeper = gravitymodulekeeper.NewKeeper( - // appCodec, - // app.GetSubspace(gravitymoduletypes.ModuleName), - // app.AccountKeeper, - // app.StakingKeeper, - // app.BankKeeper, - // app.SlashingKeeper, - // app.DistrKeeper, - // app.EvmKeeper, - // app.TransferKeeper, - // gravitymodulekeeper.NewGravityStoreGetter(keys[gravitymoduletypes.StoreKey]), - // ) + app.ValsetKeeper.SnapshotListeners = []valsetmoduletypes.OnSnapshotBuiltListener{ + app.EvmKeeper, + } + app.ValsetKeeper.EvmKeeper = app.EvmKeeper + + app.GravityKeeper = gravitymodulekeeper.NewKeeper( + appCodec, + app.GetSubspace(gravitymoduletypes.ModuleName), + app.AccountKeeper, + app.StakingKeeper, + app.BankKeeper, + app.SlashingKeeper, + app.DistrKeeper, + app.TransferKeeper, + app.EvmKeeper, + gravitymodulekeeper.NewGravityStoreGetter(keys[gravitymoduletypes.StoreKey]), + ) app.PalomaKeeper = *palomamodulekeeper.NewKeeper( appCodec, @@ -600,7 +638,9 @@ func New( app.SchedulerKeeper = *schedulermodulekeeper.NewKeeper( appCodec, - runtime.NewKVStoreService(keys[evidencetypes.StoreKey]), + keys[schedulermoduletypes.StoreKey], + memKeys[schedulermoduletypes.MemStoreKey], + app.GetSubspace(schedulermoduletypes.ModuleName), app.AccountKeeper, app.EvmKeeper, []xchain.Bridge{ @@ -608,15 +648,14 @@ func New( }, ) - // app.TreasuryKeeper = *treasurymodulekeeper.NewKeeper( - // appCodec, - // keys[treasurymoduletypes.StoreKey], - // memKeys[treasurymoduletypes.MemStoreKey], - // app.GetSubspace("" /*schedulermoduletypes.ModuleName*/), - // app.BankKeeper, - // app.AccountKeeper, - // nil, // app.SchedulerKeeper, - // ) + app.TreasuryKeeper = *treasurymodulekeeper.NewKeeper( + appCodec, + runtime.NewKVStoreService(keys[treasurymoduletypes.StoreKey]), + app.GetSubspace(schedulermoduletypes.ModuleName), + app.BankKeeper, + app.AccountKeeper, + app.SchedulerKeeper, + ) app.ScopedConsensusKeeper = scopedConsensusKeeper @@ -624,7 +663,9 @@ func New( govRouter. AddRoute(govtypes.RouterKey, govv1beta1.ProposalHandler). AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.ParamsKeeper)). - AddRoute(evmmoduletypes.RouterKey, evm.NewReferenceChainReferenceIDProposalHandler(app.EvmKeeper)) + AddRoute(evmmoduletypes.RouterKey, evm.NewReferenceChainReferenceIDProposalHandler(app.EvmKeeper)). + AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.IBCKeeper.ClientKeeper)). + AddRoute(treasurymoduletypes.RouterKey, treasurymodule.NewFeeProposalHandler(app.TreasuryKeeper)) // Example of setting gov params: govKeeper := govkeeper.NewKeeper( @@ -734,11 +775,11 @@ func New( evmModule := evm.NewAppModule(appCodec, app.EvmKeeper, app.AccountKeeper, app.BankKeeper) consensusModule := consensusmodule.NewAppModule(appCodec, app.ConsensusKeeper, app.AccountKeeper, app.BankKeeper) - // valsetModule := valsetmodule.NewAppModule(appCodec, app.ValsetKeeper, app.AccountKeeper, app.BankKeeper) + valsetModule := valsetmodule.NewAppModule(appCodec, app.ValsetKeeper, app.AccountKeeper, app.BankKeeper) schedulerModule := schedulermodule.NewAppModule(appCodec, app.SchedulerKeeper, app.AccountKeeper, app.BankKeeper) palomaModule := palomamodule.NewAppModule(appCodec, app.PalomaKeeper, app.AccountKeeper, app.BankKeeper) - // gravityModule := gravitymodule.NewAppModule(appCodec, app.GravityKeeper, app.BankKeeper) - // treasuryModule := treasurymodule.NewAppModule(appCodec, app.TreasuryKeeper, app.AccountKeeper, app.BankKeeper) + gravityModule := gravitymodule.NewAppModule(appCodec, app.GravityKeeper, app.BankKeeper) + treasuryModule := treasurymodule.NewAppModule(appCodec, app.TreasuryKeeper, app.AccountKeeper, app.BankKeeper) app.ModuleManager = module.NewManager( genutil.NewAppModule( app.AccountKeeper, @@ -762,11 +803,11 @@ func New( params.NewAppModule(app.ParamsKeeper), schedulerModule, consensusModule, - // valsetModule, evmModule, - // gravityModule, + valsetModule, + gravityModule, palomaModule, - // treasuryModule, + treasuryModule, wasm.NewAppModule(appCodec, &app.wasmKeeper, app.StakingKeeper, app.AccountKeeper, app.BankKeeper, app.MsgServiceRouter(), app.GetSubspace(wasm.ModuleName)), ibc.NewAppModule(app.IBCKeeper), transfer.NewAppModule(app.TransferKeeper), @@ -785,6 +826,7 @@ func New( }, ), }) + app.BasicModuleManager.RegisterLegacyAminoCodec(legacyAmino) app.BasicModuleManager.RegisterInterfaces(interfaceRegistry) // During begin block slashing happens after distr.BeginBlocker so that @@ -809,12 +851,12 @@ func New( authtypes.ModuleName, vestingtypes.ModuleName, genutiltypes.ModuleName, - // valsetmoduletypes.ModuleName, + valsetmoduletypes.ModuleName, palomamoduletypes.ModuleName, evmmoduletypes.ModuleName, wasmtypes.ModuleName, - // gravitymoduletypes.ModuleName, - // treasurymoduletypes.ModuleName, + gravitymoduletypes.ModuleName, + treasurymoduletypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, icatypes.ModuleName, @@ -841,17 +883,16 @@ func New( authtypes.ModuleName, vestingtypes.ModuleName, genutiltypes.ModuleName, - // valsetmoduletypes.ModuleName, + valsetmoduletypes.ModuleName, palomamoduletypes.ModuleName, evmmoduletypes.ModuleName, wasmtypes.ModuleName, - // evmmoduletypes.ModuleName, - // gravitymoduletypes.ModuleName, + gravitymoduletypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, icatypes.ModuleName, ibcfeetypes.ModuleName, - // treasurymoduletypes.ModuleName, + treasurymoduletypes.ModuleName, consensusparamtypes.ModuleName, ) @@ -879,7 +920,7 @@ func New( ibctransfertypes.ModuleName, schedulermoduletypes.ModuleName, consensusmoduletypes.ModuleName, - // valsetmoduletypes.ModuleName, + valsetmoduletypes.ModuleName, palomamoduletypes.ModuleName, ibctransfertypes.ModuleName, ibcexported.ModuleName, @@ -887,9 +928,8 @@ func New( ibcfeetypes.ModuleName, evmmoduletypes.ModuleName, wasmtypes.ModuleName, - // evmmoduletypes.ModuleName, - // gravitymoduletypes.ModuleName, - // treasurymoduletypes.ModuleName, + gravitymoduletypes.ModuleName, + treasurymoduletypes.ModuleName, consensusparamtypes.ModuleName, ) @@ -1134,10 +1174,10 @@ func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino paramsKeeper.Subspace(icacontrollertypes.SubModuleName) paramsKeeper.Subspace(schedulermoduletypes.ModuleName) paramsKeeper.Subspace(consensusmoduletypes.ModuleName) - // paramsKeeper.Subspace(valsetmoduletypes.ModuleName) + paramsKeeper.Subspace(valsetmoduletypes.ModuleName) paramsKeeper.Subspace(wasmtypes.ModuleName) paramsKeeper.Subspace(evmmoduletypes.ModuleName) - // paramsKeeper.Subspace(gravitymoduletypes.ModuleName) + paramsKeeper.Subspace(gravitymoduletypes.ModuleName) return paramsKeeper } diff --git a/app/app_setup.go b/app/app_setup.go index 5c7f9982..b0edb37b 100644 --- a/app/app_setup.go +++ b/app/app_setup.go @@ -57,7 +57,6 @@ var DefaultConsensusParams = &tmproto.ConsensusParams{ func NewTestApp(t testing, isCheckTx bool) TestApp { db := dbm.NewMemDB() - encCfg := MakeEncodingConfig() oldVersion := version.Version version.Version = "v5.1.6" @@ -92,7 +91,6 @@ func NewTestApp(t testing, isCheckTx bool) TestApp { db, nil, true, - encCfg, appOptions, ) diff --git a/app/simulation_test.go b/app/simulation_test.go index dca1e5dd..536b2b72 100644 --- a/app/simulation_test.go +++ b/app/simulation_test.go @@ -43,8 +43,6 @@ func BenchmarkSimulation(b *testing.B) { require.NoError(b, err) }) - encCfg := palomaapp.MakeEncodingConfig() - appOptions := make(simtestutil.AppOptionsMap, 0) appOptions[flags.FlagHome] = palomaapp.DefaultNodeHome appOptions[server.FlagInvCheckPeriod] = 0 @@ -54,7 +52,6 @@ func BenchmarkSimulation(b *testing.B) { db, nil, true, - encCfg, appOptions, ) diff --git a/cmd/palomad/root.go b/cmd/palomad/root.go index eed43f23..78adc857 100644 --- a/cmd/palomad/root.go +++ b/cmd/palomad/root.go @@ -29,6 +29,7 @@ func NewRootCmd() *cobra.Command { // set Bech32 address configuration params.SetAddressConfig() encCfg := palomaapp.MakeEncodingConfig() + tempApp := palomaapp.New(cosmoslog.NewNopLogger(), db.NewMemDB(), io.MultiWriter(), true, encCfg, db.OptionsMap{}) initClientCtx := client.Context{}. WithCodec(encCfg.Codec). @@ -66,6 +67,7 @@ func NewRootCmd() *cobra.Command { customAppTemplate, customAppConfig := initAppConfig() customTMConfig := initCometBFTConfig() + if err := server.InterceptConfigsPreRunHandler(cmd, customAppTemplate, customAppConfig, customTMConfig); err != nil { return err } diff --git a/go.mod b/go.mod index 799e6b7f..5894c4ac 100644 --- a/go.mod +++ b/go.mod @@ -3,20 +3,20 @@ module github.com/palomachain/paloma go 1.21 require ( - cosmossdk.io/errors v1.0.0 + cosmossdk.io/errors v1.0.0 // indirect cosmossdk.io/math v1.2.0 github.com/CosmWasm/wasmd v0.50.0-rc.0 github.com/CosmWasm/wasmvm v1.5.0 // indirect github.com/VolumeFi/whoops v0.7.2 github.com/cometbft/cometbft v0.38.1 - github.com/cometbft/cometbft-db v0.8.0 - github.com/cosmos/cosmos-proto v1.0.0-beta.3 + github.com/cometbft/cometbft-db v0.8.0 // indirect + github.com/cosmos/cosmos-proto v1.0.0-beta.3 // indirect github.com/cosmos/cosmos-sdk v0.50.1 github.com/cosmos/gogoproto v1.4.11 - github.com/gogo/protobuf v1.3.2 - github.com/golang/protobuf v1.5.3 - github.com/gorilla/mux v1.8.1 - github.com/grpc-ecosystem/grpc-gateway v1.16.0 + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/protobuf v1.5.3 // indirect + github.com/gorilla/mux v1.8.1 // indirect + github.com/grpc-ecosystem/grpc-gateway v1.16.0 // indirect github.com/huandu/skiplist v1.2.0 github.com/onsi/gomega v1.29.0 // indirect github.com/sirupsen/logrus v1.9.3 // indirect @@ -25,12 +25,11 @@ require ( github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.17.0 github.com/stretchr/testify v1.8.4 - golang.org/x/exp v0.0.0-20231006140011-7918f672742d - golang.org/x/mod v0.13.0 - google.golang.org/genproto/googleapis/api v0.0.0-20231012201019-e917dd12ba7a - google.golang.org/grpc v1.59.0 - google.golang.org/protobuf v1.31.0 - gopkg.in/yaml.v2 v2.4.0 + golang.org/x/exp v0.0.0-20231006140011-7918f672742d // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20231012201019-e917dd12ba7a // indirect + google.golang.org/grpc v1.59.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect ) require ( @@ -40,7 +39,6 @@ require ( cosmossdk.io/x/upgrade v0.1.0 github.com/cosmos/cosmos-db v1.0.0 github.com/cosmos/ibc-go/v8 v8.0.0 - github.com/ethereum/go-ethereum v1.13.5 ) require ( @@ -53,11 +51,57 @@ require ( github.com/crate-crypto/go-kzg-4844 v0.7.0 // indirect github.com/creachadair/atomicfile v0.3.1 // indirect github.com/creachadair/tomledit v0.0.24 // indirect + github.com/distribution/reference v0.5.0 // indirect github.com/emicklei/dot v1.6.0 // indirect github.com/ethereum/c-kzg-4844 v0.4.0 // indirect + github.com/ethereum/go-ethereum v1.13.5 // indirect github.com/fatih/color v1.15.0 // indirect github.com/gofrs/flock v0.8.1 // indirect github.com/hashicorp/go-hclog v1.5.0 // indirect + github.com/hashicorp/go-metrics v0.5.2 // indirect + github.com/hashicorp/go-plugin v1.6.0 // indirect + github.com/hashicorp/yamux v0.1.1 // indirect + github.com/holiman/uint256 v1.2.3 // indirect + github.com/iancoleman/strcase v0.3.0 // indirect + github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect + github.com/mmcloughlin/addchain v0.4.0 // indirect + github.com/oasisprotocol/curve25519-voi v0.0.0-20230904125328-1f23a7beb09a // indirect + github.com/oklog/run v1.1.0 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/sagikazarmark/locafero v0.3.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/supranational/blst v0.3.11 // indirect + go.uber.org/multierr v1.11.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20231030173426-d783a09b4405 // indirect + gotest.tools/v3 v3.5.1 // indirect + rsc.io/tmplfunc v0.0.3 // indirect +) + +require ( + cosmossdk.io/x/evidence v0.1.0 + cosmossdk.io/x/feegrant v0.1.0 + cosmossdk.io/x/tx v0.12.0 + cosmossdk.io/x/upgrade v0.1.0 + github.com/cosmos/cosmos-db v1.0.0 + github.com/cosmos/ibc-go/v8 v8.0.0 + github.com/ethereum/go-ethereum v1.13.5 +) + +require ( + cosmossdk.io/collections v0.4.0 // indirect + github.com/Microsoft/go-winio v0.6.1 // indirect + github.com/bits-and-blooms/bitset v1.8.0 // indirect + github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect + github.com/consensys/bavard v0.1.13 // indirect + github.com/consensys/gnark-crypto v0.12.1 // indirect + github.com/crate-crypto/go-kzg-4844 v0.7.0 // indirect + github.com/creachadair/atomicfile v0.3.1 // indirect + github.com/creachadair/tomledit v0.0.24 // indirect + github.com/emicklei/dot v1.6.0 // indirect + github.com/ethereum/c-kzg-4844 v0.4.0 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/hashicorp/go-hclog v1.5.0 // indirect github.com/hashicorp/go-metrics v0.5.1 // indirect github.com/hashicorp/go-plugin v1.5.2 // indirect github.com/hashicorp/yamux v0.1.1 // indirect @@ -88,10 +132,10 @@ require ( ) require ( - cloud.google.com/go v0.110.8 // indirect - cloud.google.com/go/compute v1.23.1 // indirect + cloud.google.com/go v0.110.10 // indirect + cloud.google.com/go/compute v1.23.3 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect - cloud.google.com/go/iam v1.1.3 // indirect + // cloud.google.com/go/iam v1.1.5 // indirect cloud.google.com/go/storage v1.30.1 // indirect cosmossdk.io/api v0.7.3-0.20231029200940-6af7f30bfd54 // indirect cosmossdk.io/core v0.12.0 // indirect @@ -101,23 +145,21 @@ require ( cosmossdk.io/tools/confix v0.1.0 filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect - github.com/99designs/keyring v1.2.1 // indirect + github.com/99designs/keyring v1.2.2 // indirect github.com/DataDog/zstd v1.5.5 // indirect - github.com/StackExchange/wmi v1.2.1 // indirect - github.com/VictoriaMetrics/fastcache v1.12.1 // indirect github.com/aws/aws-sdk-go v1.44.224 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect github.com/bgentry/speakeasy v0.1.1-0.20220910012023-760eaf8b6816 // indirect github.com/btcsuite/btcd/btcec/v2 v2.3.2 // indirect - github.com/cenkalti/backoff/v4 v4.1.3 // indirect + github.com/cenkalti/backoff/v4 v4.2.1 // indirect github.com/cespare/xxhash v1.1.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chzyer/readline v1.5.1 // indirect github.com/cockroachdb/apd/v2 v2.0.2 // indirect github.com/cockroachdb/errors v1.11.1 // indirect github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect - github.com/cockroachdb/pebble v0.0.0-20231102162011-844f0582c2eb // indirect + github.com/cockroachdb/pebble v0.0.0-20231122205016-4cbc644681f2 // indirect github.com/cockroachdb/redact v1.1.5 // indirect github.com/cosmos/btcutil v1.0.5 // indirect github.com/cosmos/go-bip39 v1.0.0 // indirect @@ -126,9 +168,8 @@ require ( github.com/cosmos/ibc-go/modules/capability v1.0.0 github.com/cosmos/ics23/go v0.10.0 // indirect github.com/cosmos/ledger-cosmos-go v0.13.3 // indirect - github.com/danieljoos/wincred v1.1.2 // indirect + github.com/danieljoos/wincred v1.2.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect - github.com/deckarep/golang-set/v2 v2.1.0 // indirect github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect github.com/dgraph-io/badger/v2 v2.2007.4 // indirect @@ -137,9 +178,9 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/dvsekhvalnov/jose2go v1.5.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect - github.com/fsnotify/fsnotify v1.6.0 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect github.com/getsentry/sentry-go v0.25.0 // indirect - github.com/go-kit/kit v0.12.0 // indirect + github.com/go-kit/kit v0.13.0 // indirect github.com/go-kit/log v0.2.1 // indirect github.com/go-logfmt/logfmt v0.6.0 // indirect github.com/go-logr/logr v1.3.0 // indirect @@ -148,20 +189,19 @@ require ( github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect github.com/gogo/googleapis v1.4.1 // indirect - github.com/golang/glog v1.1.2 // indirect + github.com/golang/glog v1.2.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/mock v1.6.0 // indirect github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect github.com/google/btree v1.1.2 // indirect github.com/google/go-cmp v0.6.0 // indirect github.com/google/orderedcode v0.0.1 // indirect - github.com/google/pprof v0.0.0-20230228050547-1710fef4ab10 // indirect github.com/google/s2a-go v0.1.7 // indirect - github.com/google/uuid v1.3.1 // indirect - github.com/googleapis/enterprise-certificate-proxy v0.3.1 // indirect + github.com/google/uuid v1.4.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect github.com/googleapis/gax-go/v2 v2.12.0 // indirect github.com/gorilla/handlers v1.5.2 // indirect - github.com/gorilla/websocket v1.5.0 // indirect + github.com/gorilla/websocket v1.5.1 // indirect github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 // indirect github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect @@ -172,23 +212,20 @@ require ( github.com/hashicorp/golang-lru v1.0.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hdevalence/ed25519consensus v0.1.0 // indirect - github.com/holiman/bloomfilter/v2 v2.0.3 // indirect - github.com/holiman/uint256 v1.2.3 // indirect github.com/improbable-eng/grpc-web v0.15.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/jmhodges/levigo v1.0.0 // indirect - github.com/klauspost/compress v1.17.2 // indirect + github.com/klauspost/compress v1.17.3 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect - github.com/lib/pq v1.10.7 // indirect + github.com/lib/pq v1.10.9 // indirect github.com/libp2p/go-buffer-pool v0.1.0 // indirect - github.com/linxGnu/grocksdb v1.8.4 // indirect + github.com/linxGnu/grocksdb v1.8.5 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/manifoldco/promptui v0.9.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect - github.com/mattn/go-runewidth v0.0.13 // indirect github.com/minio/highwayhash v1.0.2 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-testing-interface v1.14.1 // indirect @@ -206,39 +243,36 @@ require ( github.com/prometheus/procfs v0.12.0 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect - github.com/rs/cors v1.8.3 // indirect + github.com/rs/cors v1.10.1 // indirect github.com/rs/zerolog v1.31.0 // indirect github.com/sasha-s/go-deadlock v0.3.1 // indirect - github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect github.com/spf13/afero v1.10.0 // indirect github.com/stretchr/objx v0.5.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect github.com/tendermint/go-amino v0.16.0 // indirect github.com/tidwall/btree v1.7.0 // indirect - github.com/tklauser/go-sysconf v0.3.12 // indirect - github.com/tklauser/numcpus v0.6.1 // indirect github.com/ulikunitz/xz v0.5.11 // indirect github.com/zondax/hid v0.9.2 // indirect github.com/zondax/ledger-go v0.14.3 // indirect - go.etcd.io/bbolt v1.3.7 // indirect + go.etcd.io/bbolt v1.3.8 // indirect go.opencensus.io v0.24.0 // indirect - golang.org/x/crypto v0.14.0 // indirect - golang.org/x/net v0.17.0 // indirect - golang.org/x/oauth2 v0.12.0 // indirect + golang.org/x/crypto v0.15.0 // indirect + golang.org/x/net v0.18.0 // indirect + golang.org/x/oauth2 v0.13.0 // indirect golang.org/x/sync v0.5.0 // indirect golang.org/x/sys v0.14.0 // indirect - golang.org/x/term v0.13.0 // indirect - golang.org/x/text v0.13.0 // indirect + golang.org/x/term v0.14.0 // indirect + golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.14.0 // indirect golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect - google.golang.org/api v0.143.0 // indirect + // google.golang.org/api v0.149.0 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20231016165738-49dd2c1f3d0b // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20231030173426-d783a09b4405 // indirect + // google.golang.org/genproto v0.0.0-20231120223509-83a465c0220f // indirect + // google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - nhooyr.io/websocket v1.8.6 // indirect + nhooyr.io/websocket v1.8.10 // indirect pgregory.net/rapid v1.1.0 // indirect sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/go.sum b/go.sum index ee04293c..092aef66 100644 --- a/go.sum +++ b/go.sum @@ -34,6 +34,7 @@ cloud.google.com/go v0.102.1/go.mod h1:XZ77E9qnTEnrgEOvr4xzfdX5TRo7fB4T2F4O6+34h cloud.google.com/go v0.104.0/go.mod h1:OO6xxXdJyvuJPcEPBLN9BJPD+jep5G1+2U5B5gkRYtA= cloud.google.com/go v0.110.8 h1:tyNdfIxjzaWctIiLYOTalaLKZ17SI44SKFW26QbOhME= cloud.google.com/go v0.110.8/go.mod h1:Iz8AkXJf1qmxC3Oxoep8R1T36w8B92yU29PcBhHO5fk= +cloud.google.com/go v0.110.10/go.mod h1:v1OoFqYxiBkUrruItNM3eT4lLByNjxmJSV/xDKJNnic= cloud.google.com/go/aiplatform v1.22.0/go.mod h1:ig5Nct50bZlzV6NvKaTwmplLLddFx0YReh9WfTO5jKw= cloud.google.com/go/aiplatform v1.24.0/go.mod h1:67UUvRBKG6GTayHKV8DBv2RtR1t93YRu5B1P3x99mYY= cloud.google.com/go/analytics v0.11.0/go.mod h1:DjEWCu41bVbYcKyvlws9Er60YE4a//bK6mnhWvQeFNI= @@ -72,6 +73,7 @@ cloud.google.com/go/compute v1.7.0/go.mod h1:435lt8av5oL9P3fv1OEzSbSUe+ybHXGMPQH cloud.google.com/go/compute v1.10.0/go.mod h1:ER5CLbMxl90o2jtNbGSbtfOpQKR0t15FOtRsugnLrlU= cloud.google.com/go/compute v1.23.1 h1:V97tBoDaZHb6leicZ1G6DLK2BAaZLJ/7+9BB/En3hR0= cloud.google.com/go/compute v1.23.1/go.mod h1:CqB3xpmPKKt3OJpW2ndFIXnA9A4xAy/F3Xp1ixncW78= +cloud.google.com/go/compute v1.23.3/go.mod h1:VCgBUoMnIVIR0CscqQiPJLAG25E3ZRZMzcFZeQ+h8CI= cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY= cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA= cloud.google.com/go/containeranalysis v0.5.1/go.mod h1:1D92jd8gRR/c0fGMlymRgxWD3Qw9C1ff6/T7mLgVL8I= @@ -113,6 +115,7 @@ cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp cloud.google.com/go/iam v0.5.0/go.mod h1:wPU9Vt0P4UmCux7mqtRu6jcpPAb74cP1fh50J3QpkUc= cloud.google.com/go/iam v1.1.3 h1:18tKG7DzydKWUnLjonWcJO6wjSCAtzh4GcRKlH/Hrzc= cloud.google.com/go/iam v1.1.3/go.mod h1:3khUlaBXfPKKe7huYgEpDn6FtgRyMEqbkvBxrQyY5SE= +cloud.google.com/go/iam v1.1.5/go.mod h1:rB6P/Ic3mykPbFio+vo7403drjlgvoWfYpJhMXEbzv8= cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic= cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI= cloud.google.com/go/lifesciences v0.5.0/go.mod h1:3oIKy8ycWGPUyZDR/8RNnTOYevhaMLqh5vLUXs9zvT8= @@ -304,6 +307,8 @@ github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QH github.com/cenkalti/backoff/v4 v4.1.1/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.2.1/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= @@ -347,6 +352,7 @@ github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b h1:r6VH0faHjZe github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b/go.mod h1:Vz9DsVWQQhf3vs21MhPMZpMGSht7O/2vFW2xusFUVOs= github.com/cockroachdb/pebble v0.0.0-20231102162011-844f0582c2eb h1:6Po+YYKT5B5ZXN0wd2rwFBaebM0LufPf8p4zxOd48Kg= github.com/cockroachdb/pebble v0.0.0-20231102162011-844f0582c2eb/go.mod h1:acMRUGd/BK8AUmQNK3spUCCGzFLZU2bSST3NMXSq2Kc= +github.com/cockroachdb/pebble v0.0.0-20231122205016-4cbc644681f2/go.mod h1:acMRUGd/BK8AUmQNK3spUCCGzFLZU2bSST3NMXSq2Kc= github.com/cockroachdb/redact v1.1.5 h1:u1PMllDkdFfPWaNGMyLD1+so+aq3uUItthCFqzwPJ30= github.com/cockroachdb/redact v1.1.5/go.mod h1:BVNblN9mBWFyMyqK1k3AAiSxhvhfK2oOZZ2lK+dpvRg= github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 h1:zuQyyAKVxetITBuuhv3BI9cMrmStnpT18zmgmTxunpo= @@ -408,6 +414,7 @@ github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7Do github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= +github.com/danieljoos/wincred v1.2.0/go.mod h1:FzQLLMKBFdvu+osBrnFODiv32YGwCfx0SkRa/eYHgec= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= @@ -478,6 +485,7 @@ github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMo github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY= github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/getsentry/sentry-go v0.25.0 h1:q6Eo+hS+yoJlTO3uu/azhQadsD8V+jQn2D8VvX1eOyI= @@ -497,6 +505,8 @@ github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2 github.com/go-kit/kit v0.10.0/go.mod h1:xUsJbQ/Fp4kEt7AFgCuvyX4a71u8h9jB8tj/ORgOZ7o= github.com/go-kit/kit v0.12.0 h1:e4o3o3IsBfAKQh5Qbbiqyfu97Ku7jrO/JbohvztANh4= github.com/go-kit/kit v0.12.0/go.mod h1:lHd+EkCZPIwYItmGDDRdhinkzX2A1sj+M9biaEaizzs= +github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU= +github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-kit/log v0.2.1 h1:MRVx0/zhvdseW+Gza6N9rVzU/IVzaeE1SFI4raAhmBU= github.com/go-kit/log v0.2.1/go.mod h1:NwTd00d/i8cPZ3xOwwiv2PO5MOcx78fFErGNcVmBjv0= @@ -551,6 +561,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69 github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/glog v1.1.2 h1:DVjP2PbBOzHyzA+dn3WhHIq4NdVu3Q+pvivFICf/7fo= github.com/golang/glog v1.1.2/go.mod h1:zR+okUeTbrL6EL3xHUDxZuEtGv04p5shwip1+mL/rLQ= +github.com/golang/glog v1.2.0 h1:uCdmnmatrKCgMBlM4rMuJZWOkPDqdbZPnrMXDY4gI68= +github.com/golang/glog v1.2.0/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= @@ -652,11 +664,13 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/googleapis/enterprise-certificate-proxy v0.0.0-20220520183353-fd19c99a87aa/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= github.com/googleapis/enterprise-certificate-proxy v0.1.0/go.mod h1:17drOmN3MwGY7t0e+Ei9b45FFGA3fBs3x36SsCg1hq8= github.com/googleapis/enterprise-certificate-proxy v0.2.0/go.mod h1:8C0jb7/mgJe/9KK8Lm7X9ctZC2t60YyIpYEI16jx0Qg= github.com/googleapis/enterprise-certificate-proxy v0.3.1 h1:SBWmZhjUDRorQxrN0nwzf+AHBxnbFjViHQS4P0yVpmQ= github.com/googleapis/enterprise-certificate-proxy v0.3.1/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= @@ -682,6 +696,7 @@ github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= @@ -708,10 +723,14 @@ github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJ github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-metrics v0.5.1 h1:rfPwUqFU6uZXNvGl4hzjY8LEBsqFVU4si1H9/Hqck/U= github.com/hashicorp/go-metrics v0.5.1/go.mod h1:KEjodfebIOuBYSAe/bHTm+HChmKSxAOXPBieMLYozDE= +github.com/hashicorp/go-metrics v0.5.2 h1:ErEYO2f//CjKsUDw4SmLzelsK6L3ZmOAR/4P9iS7ruY= +github.com/hashicorp/go-metrics v0.5.2/go.mod h1:KEjodfebIOuBYSAe/bHTm+HChmKSxAOXPBieMLYozDE= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-plugin v1.5.2 h1:aWv8eimFqWlsEiMrYZdPYl+FdHaBJSN4AWwGWfT1G2Y= github.com/hashicorp/go-plugin v1.5.2/go.mod h1:w1sAEES3g3PuV/RzUrgow20W2uErMly84hhD3um1WL4= +github.com/hashicorp/go-plugin v1.6.0 h1:wgd4KxHJTVGGqWBq4QPB1i5BZNEx9BR8+OFmHDmTk8A= +github.com/hashicorp/go-plugin v1.6.0/go.mod h1:lBS5MtSSBZk0SHc66KACcjjlU6WzEVP/8pwz68aMkCI= github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-safetemp v1.0.0 h1:2HR189eFNrjHQyENnQMMpCiBAsRxzbTMIgBhEyExpmo= @@ -793,6 +812,7 @@ github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8 github.com/klauspost/compress v1.15.11/go.mod h1:QPwzmACJjUTFsnSHH934V6woptycfrDDJnH7hvFVbGM= github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/compress v1.17.3/go.mod h1:/dCuZOvVtNoHsyb+cuJD3itjs3NbnF6KH9zAO4BDxPM= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= @@ -811,12 +831,15 @@ github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/lib/pq v1.10.7 h1:p7ZhMD+KsSRozJr34udlUrhboJwWAgCg34+/ZZNvZZw= github.com/lib/pq v1.10.7/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/libp2p/go-buffer-pool v0.1.0 h1:oK4mSFcQz7cTQIfqbe4MIj9gLW+mnanjyFtc6cdF0Y8= github.com/libp2p/go-buffer-pool v0.1.0/go.mod h1:N+vh8gMqimBzdKkSMVuydVDq+UV5QTWy5HSiZacSbPg= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/linxGnu/grocksdb v1.8.4 h1:ZMsBpPpJNtRLHiKKp0mI7gW+NT4s7UgfD5xHxx1jVRo= github.com/linxGnu/grocksdb v1.8.4/go.mod h1:xZCIb5Muw+nhbDK4Y5UJuOrin5MceOuiXkVUR7vp4WY= +github.com/linxGnu/grocksdb v1.8.5/go.mod h1:xZCIb5Muw+nhbDK4Y5UJuOrin5MceOuiXkVUR7vp4WY= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= @@ -1002,6 +1025,7 @@ github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUz github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= +github.com/rs/cors v1.10.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A= github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= @@ -1116,6 +1140,8 @@ github.com/zondax/ledger-go v0.14.3/go.mod h1:IKKaoxupuB43g4NxeQmbLXv7T9AlQyie1U go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.7 h1:j+zJOnnEjF/kyHlDDgGnVL/AIqIJPq8UoB2GSNfkUfQ= go.etcd.io/bbolt v1.3.7/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= +go.etcd.io/bbolt v1.3.8 h1:xs88BrvEv273UsB79e0hcVrlUWmS0a8upikMFhSyAtA= +go.etcd.io/bbolt v1.3.8/go.mod h1:N9Mkw9X8x5fupy0IKsmuqVtoGDyxsaDlbk4Rd05IAQw= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= @@ -1163,6 +1189,8 @@ golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/crypto v0.15.0 h1:frVn1TEaCEaZcn3Tmd7Y2b5KKPaZ+I32Q2OA3kYp5TA= +golang.org/x/crypto v0.15.0/go.mod h1:4ChreQoLWfG3xLDer1WdlH5NdlQ3+mwnQq1YTKY+72g= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1271,6 +1299,8 @@ golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg= +golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1298,6 +1328,8 @@ golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri golang.org/x/oauth2 v0.1.0/go.mod h1:G9FE4dLTsbXUu90h/Pf85g4w1D+SSAgR+q46nJZ8M4A= golang.org/x/oauth2 v0.12.0 h1:smVPGxink+n1ZI5pkQa8y6fZT0RW0MgCO5bFpepy4B4= golang.org/x/oauth2 v0.12.0/go.mod h1:A74bZ3aGXgCY0qaIC9Ahg6Lglin4AMAco8cIv9baba4= +golang.org/x/oauth2 v0.13.0 h1:jDDenyj+WgFtmV3zYVoi8aE2BwtXFLWOA67ZfNWftiY= +golang.org/x/oauth2 v0.13.0/go.mod h1:/JMhi4ZRXAf4HG9LiNmxvk+45+96RUlVThiH8FzNBn0= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -1433,6 +1465,8 @@ golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +golang.org/x/term v0.14.0 h1:LGK9IlZ8T9jvdy6cTdfKUCltatMFOehAQo9SRC46UQ8= +golang.org/x/term v0.14.0/go.mod h1:TySc+nGkYR6qt8km8wUhuFRTVSMIX3XPR58y2lC8vww= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1449,6 +1483,8 @@ golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k= golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -1493,6 +1529,7 @@ golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapK golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200323144430-8dcfad9e016e/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= @@ -1519,6 +1556,7 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.14.0 h1:jvNa2pY0M4r62jkRQ6RwEZZyPcymeL9XZMLBbV7U2nc= golang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg= +golang.org/x/tools v0.15.0/go.mod h1:hpksKq4dtpQWS1uQ61JkdqWM3LscIS6Slf+VVkm+wQk= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -1579,6 +1617,8 @@ google.golang.org/api v0.98.0/go.mod h1:w7wJQLTM+wvQpNf5JyEcBoxK0RH7EDrh/L4qfsuJ google.golang.org/api v0.100.0/go.mod h1:ZE3Z2+ZOr87Rx7dqFsdRQkRBk36kDtp/h+QpHbB7a70= google.golang.org/api v0.143.0 h1:o8cekTkqhywkbZT6p1UHJPZ9+9uuCAJs/KYomxZB8fA= google.golang.org/api v0.143.0/go.mod h1:FoX9DO9hT7DLNn97OuoZAGSDuNAXdJRuGK98rSUgurk= +google.golang.org/api v0.149.0 h1:b2CqT6kG+zqJIVKRQ3ELJVLN1PwHZ6DJ3dW8yl82rgY= +google.golang.org/api v0.149.0/go.mod h1:Mwn1B7JTXrzXtnvmzQE2BD6bYZQ8DShKZDZbeN9I7qI= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= @@ -1808,6 +1848,7 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9 honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= nhooyr.io/websocket v1.8.6 h1:s+C3xAMLwGmlI31Nyn/eAehUlZPwfYZu2JXM621Q5/k= nhooyr.io/websocket v1.8.6/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +nhooyr.io/websocket v1.8.10/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= pgregory.net/rapid v1.1.0 h1:CMa0sjHSru3puNx+J0MIAuiiEV4N0qj8/cMWGBBCsjw= pgregory.net/rapid v1.1.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= diff --git a/proto/palomachain/paloma/gravity/attestation.proto b/proto/palomachain/paloma/gravity/attestation.proto index f2e1c547..6d4102c1 100644 --- a/proto/palomachain/paloma/gravity/attestation.proto +++ b/proto/palomachain/paloma/gravity/attestation.proto @@ -50,7 +50,7 @@ message Attestation { message ERC20Token { string contract = 1; string amount = 2 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.customtype) = "cosmossdk.io/math.Int", (gogoproto.nullable) = false ]; string chain_reference_id = 3; diff --git a/proto/palomachain/paloma/treasury/params.proto b/proto/palomachain/paloma/treasury/params.proto index 4c8473ad..5b9e1604 100644 --- a/proto/palomachain/paloma/treasury/params.proto +++ b/proto/palomachain/paloma/treasury/params.proto @@ -1,11 +1,9 @@ syntax = "proto3"; package palomachain.paloma.treasury; -import "gogoproto/gogo.proto"; option go_package = "github.com/palomachain/paloma/x/treasury/types"; // Params defines the parameters for the module. -message Params { - option (gogoproto.goproto_stringer) = false; +message Params { } \ No newline at end of file diff --git a/testutil/keeper/valset.go b/testutil/keeper/valset.go index 78c1e0bf..6e6f1f22 100644 --- a/testutil/keeper/valset.go +++ b/testutil/keeper/valset.go @@ -11,6 +11,7 @@ import ( tmdb "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" typesparams "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/palomachain/paloma/x/valset/keeper" @@ -21,6 +22,7 @@ import ( func ValsetKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { storeKey := storetypes.NewKVStoreKey(types.StoreKey) + storeService := runtime.NewKVStoreService(storeKey) memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) db := tmdb.NewMemDB() @@ -40,7 +42,7 @@ func ValsetKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { ) k := keeper.NewKeeper( cdc, - storeKey, + storeService, memStoreKey, paramsSubspace, nil, diff --git a/util/keeper/address.go b/util/keeper/address.go new file mode 100644 index 00000000..7e2fa21b --- /dev/null +++ b/util/keeper/address.go @@ -0,0 +1,8 @@ +package keeper + +import "cosmossdk.io/core/address" + +func ValAddressFromBech32(addressCodec address.Codec, valAddr string) ([]byte, error) { + bz, err := addressCodec.StringToBytes(valAddr) + return bz, err +} diff --git a/x/evm/types/tx.pb.go b/x/evm/types/tx.pb.go index 2245247b..5b3956f0 100644 --- a/x/evm/types/tx.pb.go +++ b/x/evm/types/tx.pb.go @@ -269,38 +269,39 @@ func init() { func init() { proto.RegisterFile("palomachain/paloma/evm/tx.proto", fileDescriptor_631cfc68eb1fd278) } var fileDescriptor_631cfc68eb1fd278 = []byte{ - // 488 bytes of a gzipped FileDescriptorProto + // 497 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x54, 0xcd, 0x6e, 0xd3, 0x40, - 0x10, 0xce, 0xa6, 0x69, 0x0a, 0xdb, 0x03, 0x68, 0x55, 0x15, 0x63, 0x81, 0x6b, 0x45, 0xa2, 0x0d, - 0x1c, 0x6c, 0x51, 0x24, 0xc4, 0x05, 0x21, 0xa5, 0x39, 0xb4, 0x48, 0x2e, 0x92, 0x73, 0xe3, 0x82, - 0x36, 0x9b, 0xc1, 0xb5, 0x94, 0xf5, 0x18, 0xef, 0xd6, 0x24, 0xaf, 0xc0, 0x89, 0x37, 0xe0, 0x25, - 0x78, 0x88, 0x1e, 0x7b, 0xe4, 0x84, 0x50, 0x22, 0x5e, 0x03, 0xa1, 0x78, 0xdd, 0xca, 0x05, 0x27, - 0xad, 0xd4, 0x53, 0x66, 0xbe, 0x9f, 0x68, 0xe6, 0xdb, 0x5d, 0xd3, 0x9d, 0x94, 0x8f, 0x51, 0x72, - 0x71, 0xc2, 0xe3, 0xc4, 0x37, 0xb5, 0x0f, 0xb9, 0xf4, 0xf5, 0xc4, 0x4b, 0x33, 0xd4, 0xc8, 0xb6, - 0x2b, 0x02, 0xcf, 0xd4, 0x1e, 0xe4, 0xd2, 0xde, 0x8a, 0x30, 0xc2, 0x42, 0xe2, 0x2f, 0x2a, 0xa3, - 0xb6, 0x1f, 0x0a, 0x54, 0x12, 0xd5, 0x07, 0x43, 0x98, 0xa6, 0xa4, 0x1e, 0x98, 0xce, 0x97, 0x2a, - 0xf2, 0xf3, 0xe7, 0x8b, 0x9f, 0x92, 0xd8, 0xad, 0x19, 0x21, 0xe7, 0x63, 0x05, 0xda, 0x17, 0x28, - 0x25, 0x26, 0x46, 0xd7, 0xf9, 0x43, 0xa8, 0x1b, 0xa8, 0xa8, 0x0f, 0xe9, 0x18, 0xa7, 0xc7, 0xf0, - 0x79, 0x20, 0x79, 0xa6, 0x0f, 0x30, 0xd1, 0x19, 0x17, 0x3a, 0x84, 0x4f, 0xa7, 0xa0, 0x34, 0x7b, - 0x44, 0x37, 0x44, 0x06, 0x5c, 0x63, 0x66, 0x11, 0x97, 0x74, 0xef, 0xf6, 0x9a, 0x16, 0x09, 0x2f, - 0x20, 0xb6, 0x45, 0xd7, 0x75, 0xac, 0xc7, 0x60, 0x35, 0x17, 0x5c, 0x68, 0x1a, 0xe6, 0xd2, 0xcd, - 0x11, 0x28, 0x91, 0xc5, 0xa9, 0x8e, 0x31, 0xb1, 0xd6, 0x0a, 0xae, 0x0a, 0x31, 0x8b, 0x6e, 0xf0, - 0x61, 0xfc, 0x76, 0xf0, 0xee, 0xd8, 0x6a, 0x15, 0xec, 0x45, 0xbb, 0xf0, 0x0e, 0xa7, 0x1a, 0x04, - 0x8e, 0xe0, 0x10, 0x26, 0xd6, 0xba, 0xf1, 0x56, 0x20, 0x76, 0x48, 0xef, 0x48, 0xd0, 0x7c, 0xc4, - 0x35, 0xb7, 0xda, 0x2e, 0xe9, 0x6e, 0xee, 0xef, 0x7a, 0x35, 0x99, 0x9a, 0x8d, 0xbd, 0x40, 0x45, - 0x41, 0xa9, 0xee, 0xb5, 0xce, 0x7e, 0xee, 0x34, 0xc2, 0x4b, 0x77, 0xc7, 0xa5, 0xce, 0xb2, 0xe5, - 0x55, 0x8a, 0x89, 0x82, 0xce, 0x6f, 0x42, 0xf7, 0x02, 0x15, 0x85, 0x20, 0x31, 0x87, 0x2b, 0x12, - 0x63, 0x94, 0x90, 0x5c, 0x26, 0x65, 0xd3, 0xf6, 0x00, 0x92, 0x11, 0x54, 0x83, 0x2a, 0x11, 0xd6, - 0xa5, 0xf7, 0x54, 0xd5, 0x7d, 0xd4, 0x2f, 0x12, 0x6b, 0x85, 0xff, 0xc2, 0xec, 0x19, 0xbd, 0x5f, - 0xac, 0x11, 0xc2, 0x47, 0xc8, 0x20, 0x11, 0x70, 0xd4, 0x2f, 0x03, 0xfc, 0x0f, 0xbf, 0x92, 0x44, - 0xeb, 0x56, 0x49, 0xec, 0xd1, 0x27, 0xd7, 0xec, 0x68, 0x02, 0xd9, 0xff, 0xde, 0xa4, 0x6b, 0x81, - 0x8a, 0xd8, 0x17, 0x42, 0xb7, 0xeb, 0xb3, 0x63, 0xaf, 0xbc, 0xfa, 0x1b, 0xee, 0x5d, 0x77, 0xd7, - 0xec, 0x97, 0xcb, 0x9c, 0xab, 0x4f, 0x89, 0x7d, 0x23, 0xf4, 0xf1, 0xca, 0xf1, 0xd9, 0x9b, 0x15, - 0x33, 0xdd, 0xe4, 0x70, 0xed, 0xd7, 0xcb, 0xfe, 0xe0, 0x46, 0xb1, 0xf5, 0x0e, 0xce, 0x66, 0x0e, - 0x39, 0x9f, 0x39, 0xe4, 0xd7, 0xcc, 0x21, 0x5f, 0xe7, 0x4e, 0xe3, 0x7c, 0xee, 0x34, 0x7e, 0xcc, - 0x9d, 0xc6, 0xfb, 0xa7, 0x51, 0xac, 0x4f, 0x4e, 0x87, 0x9e, 0x40, 0xe9, 0xd7, 0xbc, 0xdb, 0x89, - 0xf9, 0x78, 0x4c, 0x53, 0x50, 0xc3, 0x76, 0xf1, 0x6c, 0x5f, 0xfc, 0x0d, 0x00, 0x00, 0xff, 0xff, - 0x49, 0xba, 0x57, 0x50, 0x63, 0x04, 0x00, 0x00, + 0x10, 0xce, 0xa6, 0x69, 0x0a, 0xdb, 0x03, 0x68, 0x55, 0x15, 0x63, 0x81, 0x6b, 0x05, 0xd1, 0x06, + 0x0e, 0xb6, 0x28, 0x12, 0xe2, 0x82, 0x90, 0xd2, 0x1c, 0x5a, 0x24, 0x17, 0xc9, 0xb9, 0x71, 0x41, + 0x9b, 0xcd, 0xe0, 0x5a, 0xca, 0x7a, 0x8c, 0x77, 0x6b, 0x92, 0x57, 0xe0, 0xc4, 0x1b, 0xf0, 0x12, + 0x3c, 0x44, 0x8f, 0x3d, 0x72, 0x42, 0x28, 0x11, 0xaf, 0x81, 0x50, 0xbc, 0x6e, 0xe5, 0x82, 0x93, + 0x56, 0xe2, 0x94, 0x9d, 0xef, 0x27, 0x9e, 0xf9, 0xd6, 0x63, 0xba, 0x93, 0xf2, 0x31, 0x4a, 0x2e, + 0x4e, 0x78, 0x9c, 0xf8, 0xe6, 0xec, 0x43, 0x2e, 0x7d, 0x3d, 0xf1, 0xd2, 0x0c, 0x35, 0xb2, 0xed, + 0x8a, 0xc0, 0x33, 0x67, 0x0f, 0x72, 0x69, 0x6f, 0x45, 0x18, 0x61, 0x21, 0xf1, 0x17, 0x27, 0xa3, + 0xb6, 0xef, 0x0b, 0x54, 0x12, 0xd5, 0x7b, 0x43, 0x98, 0xa2, 0xa4, 0xee, 0x99, 0xca, 0x97, 0x2a, + 0xf2, 0xf3, 0x67, 0x8b, 0x9f, 0x92, 0xd8, 0xad, 0x69, 0x21, 0xe7, 0x63, 0x05, 0xda, 0x17, 0x28, + 0x25, 0x26, 0xa5, 0xee, 0xd1, 0x92, 0x56, 0x53, 0x9e, 0x71, 0x59, 0x3e, 0xa5, 0xf3, 0x9b, 0x50, + 0x37, 0x50, 0x51, 0x1f, 0xd2, 0x31, 0x4e, 0x8f, 0xe1, 0xd3, 0x40, 0xf2, 0x4c, 0x1f, 0x60, 0xa2, + 0x33, 0x2e, 0x74, 0x08, 0x1f, 0x4f, 0x41, 0x69, 0xf6, 0x80, 0x6e, 0x88, 0x0c, 0xb8, 0xc6, 0xcc, + 0x22, 0x2e, 0xe9, 0xde, 0xee, 0x35, 0x2d, 0x12, 0x5e, 0x40, 0x6c, 0x8b, 0xae, 0xeb, 0x58, 0x8f, + 0xc1, 0x6a, 0x2e, 0xb8, 0xd0, 0x14, 0xcc, 0xa5, 0x9b, 0x23, 0x50, 0x22, 0x8b, 0x53, 0x1d, 0x63, + 0x62, 0xad, 0x15, 0x5c, 0x15, 0x62, 0x16, 0xdd, 0xe0, 0xc3, 0xf8, 0xcd, 0xe0, 0xed, 0xb1, 0xd5, + 0x2a, 0xd8, 0x8b, 0x72, 0xe1, 0x1d, 0x4e, 0x35, 0x08, 0x1c, 0xc1, 0x21, 0x4c, 0xac, 0x75, 0xe3, + 0xad, 0x40, 0xec, 0x90, 0xde, 0x92, 0xa0, 0xf9, 0x88, 0x6b, 0x6e, 0xb5, 0x5d, 0xd2, 0xdd, 0xdc, + 0xdf, 0xf5, 0x6a, 0x82, 0x37, 0xb1, 0x78, 0x81, 0x8a, 0x82, 0x52, 0xdd, 0x6b, 0x9d, 0xfd, 0xd8, + 0x69, 0x84, 0x97, 0xee, 0x8e, 0x4b, 0x9d, 0x65, 0xc3, 0xab, 0x14, 0x13, 0x05, 0x9d, 0x5f, 0x84, + 0xee, 0x05, 0x2a, 0x0a, 0x41, 0x62, 0x0e, 0x57, 0x24, 0xc6, 0x28, 0x21, 0xb9, 0x4c, 0xca, 0xa6, + 0xed, 0x01, 0x24, 0x23, 0xa8, 0x06, 0x55, 0x22, 0xac, 0x4b, 0xef, 0xa8, 0xaa, 0xfb, 0xa8, 0x5f, + 0x24, 0xd6, 0x0a, 0xff, 0x86, 0xd9, 0x53, 0x7a, 0xb7, 0x18, 0x23, 0x84, 0x0f, 0x90, 0x41, 0x22, + 0xe0, 0xa8, 0x5f, 0x06, 0xf8, 0x0f, 0x7e, 0x25, 0x89, 0xd6, 0x7f, 0x25, 0xb1, 0x47, 0x1f, 0x5f, + 0x33, 0xa3, 0x09, 0x64, 0xff, 0x5b, 0x93, 0xae, 0x05, 0x2a, 0x62, 0x9f, 0x09, 0xdd, 0xae, 0xcf, + 0x8e, 0xbd, 0xf4, 0xea, 0xd7, 0xc0, 0xbb, 0xee, 0x5d, 0xb3, 0x5f, 0x2c, 0x73, 0xae, 0xbe, 0x25, + 0xf6, 0x95, 0xd0, 0x87, 0x2b, 0xdb, 0x67, 0xaf, 0x57, 0xf4, 0x74, 0x93, 0xcb, 0xb5, 0x5f, 0x2d, + 0xfb, 0x83, 0x1b, 0xc5, 0xd6, 0x3b, 0x38, 0x9b, 0x39, 0xe4, 0x7c, 0xe6, 0x90, 0x9f, 0x33, 0x87, + 0x7c, 0x99, 0x3b, 0x8d, 0xf3, 0xb9, 0xd3, 0xf8, 0x3e, 0x77, 0x1a, 0xef, 0x9e, 0x44, 0xb1, 0x3e, + 0x39, 0x1d, 0x7a, 0x02, 0xa5, 0x5f, 0xb3, 0xb4, 0x13, 0xf3, 0x85, 0x99, 0xa6, 0xa0, 0x86, 0xed, + 0x62, 0x6d, 0x9f, 0xff, 0x09, 0x00, 0x00, 0xff, 0xff, 0xab, 0xda, 0x40, 0x52, 0x88, 0x04, 0x00, + 0x00, } // Reference imports to suppress errors if they are not otherwise used. diff --git a/x/gravity/abci.go b/x/gravity/abci.go index 75f61e6e..bf02360c 100644 --- a/x/gravity/abci.go +++ b/x/gravity/abci.go @@ -1,6 +1,8 @@ package gravity import ( + "context" + sdkerrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/keeper" @@ -8,7 +10,7 @@ import ( ) // EndBlocker is called at the end of every block -func EndBlocker(ctx sdk.Context, k keeper.Keeper) { +func EndBlocker(ctx context.Context, k keeper.Keeper) { // slashing(ctx, k) err := createBatch(ctx, k) @@ -33,8 +35,9 @@ func EndBlocker(ctx sdk.Context, k keeper.Keeper) { } // Create a batch of transactions for each token -func createBatch(ctx sdk.Context, k keeper.Keeper) error { - if ctx.BlockHeight()%50 == 0 { +func createBatch(ctx context.Context, k keeper.Keeper) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + if sdkCtx.BlockHeight()%50 == 0 { denoms, err := k.GetAllERC20ToDenoms(ctx) if err != nil { return err @@ -57,7 +60,7 @@ func createBatch(ctx sdk.Context, k keeper.Keeper) error { // Iterate over all attestations currently being voted on in order of nonce and // "Observe" those who have passed the threshold. Break the loop once we see // an attestation that has not passed the threshold -func attestationTally(ctx sdk.Context, k keeper.Keeper) error { +func attestationTally(ctx context.Context, k keeper.Keeper) error { attmap, keys, err := k.GetAttestationMapping(ctx) if err != nil { return err @@ -104,8 +107,9 @@ func attestationTally(ctx sdk.Context, k keeper.Keeper) error { } // cleanupTimedOutBatches deletes batches that have passed their expiration -func cleanupTimedOutBatches(ctx sdk.Context, k keeper.Keeper) error { - currentTime := uint64(ctx.BlockTime().Unix()) +func cleanupTimedOutBatches(ctx context.Context, k keeper.Keeper) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + currentTime := uint64(sdkCtx.BlockTime().Unix()) batches, err := k.GetOutgoingTxBatches(ctx) if err != nil { return err @@ -126,7 +130,7 @@ func cleanupTimedOutBatches(ctx sdk.Context, k keeper.Keeper) error { // use. This could be combined with create attestation and save some computation // but (A) pruning keeps the iteration small in the first place and (B) there is // already enough nuance in the other handler that it's best not to complicate it further -func pruneAttestations(ctx sdk.Context, k keeper.Keeper) error { +func pruneAttestations(ctx context.Context, k keeper.Keeper) error { attmap, keys, err := k.GetAttestationMapping(ctx) if err != nil { return err diff --git a/x/gravity/abci_test.go b/x/gravity/abci_test.go index 2cab9cab..511d068f 100644 --- a/x/gravity/abci_test.go +++ b/x/gravity/abci_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" @@ -53,11 +54,11 @@ func TestNonValidatorBatchConfirm(t *testing.T) { stakingMsgSvr := stakingkeeper.NewMsgServerImpl(&input.StakingKeeper) - _, err = stakingMsgSvr.CreateValidator(input.Context, keeper.NewTestMsgCreateValidator(valAddr, consPubKey, sdk.NewIntFromUint64(1))) + _, err = stakingMsgSvr.CreateValidator(input.Context, keeper.NewTestMsgCreateValidator(valAddr, consPubKey, math.NewIntFromUint64(1))) require.NoError(t, err) // Run the staking endblocker to ensure valset is correct in state - stakingkeeper.EndBlocker(input.Context, &input.StakingKeeper) + input.StakingKeeper.EndBlocker(input.Context) ethAddr, err := types.NewEthAddress("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B") if err != nil { @@ -105,7 +106,7 @@ func TestNonValidatorBatchConfirm(t *testing.T) { }) // Now remove all the stake - _, err = stakingMsgSvr.Undelegate(input.Context, keeper.NewTestMsgUnDelegateValidator(valAddr, sdk.NewIntFromUint64(1))) + _, err = stakingMsgSvr.Undelegate(input.Context, keeper.NewTestMsgUnDelegateValidator(valAddr, math.NewIntFromUint64(1))) require.NoError(t, err) EndBlocker(ctx, pk) @@ -124,7 +125,7 @@ func TestBatchTimeout(t *testing.T) { myReceiver = "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7" testERC20Address = "0x0bc529c00c6401aef6d220be8c6ea1667f6ad93e" testDenom = "ugrain" - token, e2 = types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + token, e2 = types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) require.NoError(t, e1) @@ -145,7 +146,7 @@ func TestBatchTimeout(t *testing.T) { // add some TX to the pool for i := 0; i < 6; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) diff --git a/x/gravity/client/cli/tx.go b/x/gravity/client/cli/tx.go index 0a8b276f..16c6eca7 100644 --- a/x/gravity/client/cli/tx.go +++ b/x/gravity/client/cli/tx.go @@ -3,11 +3,11 @@ package cli import ( "strconv" + sdkerrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/palomachain/paloma/x/gravity/types" vtypes "github.com/palomachain/paloma/x/valset/types" "github.com/spf13/cobra" diff --git a/x/gravity/handler.go b/x/gravity/handler.go index d37e4df6..c7adc5a2 100644 --- a/x/gravity/handler.go +++ b/x/gravity/handler.go @@ -3,40 +3,42 @@ package gravity import ( "fmt" + sdkerrors "cosmossdk.io/errors" + "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "github.com/cosmos/cosmos-sdk/types/errors" "github.com/palomachain/paloma/x/gravity/keeper" "github.com/palomachain/paloma/x/gravity/types" ) // NewHandler returns a handler for "Gravity" type messages. -func NewHandler(k keeper.Keeper) sdk.Handler { +func NewHandler(k keeper.Keeper) baseapp.MsgServiceHandler { msgServer := keeper.NewMsgServerImpl(k) return func(ctx sdk.Context, msg sdk.Msg) (*sdk.Result, error) { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { case *types.MsgSendToEth: - res, err := msgServer.SendToEth(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.SendToEth(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.MsgConfirmBatch: - res, err := msgServer.ConfirmBatch(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.ConfirmBatch(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.MsgSendToPalomaClaim: - res, err := msgServer.SendToPalomaClaim(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.SendToPalomaClaim(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.MsgBatchSendToEthClaim: - res, err := msgServer.BatchSendToEthClaim(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.BatchSendToEthClaim(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.MsgCancelSendToEth: - res, err := msgServer.CancelSendToEth(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.CancelSendToEth(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) case *types.MsgSubmitBadSignatureEvidence: - res, err := msgServer.SubmitBadSignatureEvidence(sdk.WrapSDKContext(ctx), msg) + res, err := msgServer.SubmitBadSignatureEvidence(sdk.UnwrapSDKContext(ctx), msg) return sdk.WrapServiceResult(ctx, res, err) default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, fmt.Sprintf("Unrecognized Gravity Msg type: %v", sdk.MsgTypeURL(msg))) + return nil, sdkerrors.Wrap(errorsmod.ErrUnknownRequest, fmt.Sprintf("Unrecognized Gravity Msg type: %v", sdk.MsgTypeURL(msg))) } } } diff --git a/x/gravity/handler_test.go b/x/gravity/handler_test.go index 9a05befb..8e171c2b 100644 --- a/x/gravity/handler_test.go +++ b/x/gravity/handler_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/keeper" "github.com/palomachain/paloma/x/gravity/types" @@ -19,8 +20,8 @@ func TestHandleMsgSendToEth(t *testing.T) { blockTime = time.Date(2020, 9, 14, 15, 20, 10, 0, time.UTC) blockHeight int64 = 200 testDenom = "ugrain" - startingCoinAmount, _ = sdk.NewIntFromString("150000000000000000000") - sendAmount, _ = sdk.NewIntFromString("60000000000000000000") + startingCoinAmount, _ = math.NewIntFromString("150000000000000000000") + sendAmount, _ = math.NewIntFromString("60000000000000000000") startingCoins sdk.Coins = sdk.Coins{sdk.NewCoin(testDenom, startingCoinAmount)} sendingCoin sdk.Coin = sdk.NewCoin(testDenom, sendAmount) ethDestination = "0x3c9289da00b02dC623d0D8D907619890301D26d4" diff --git a/x/gravity/keeper/attestation.go b/x/gravity/keeper/attestation.go index 001eb108..1d037dbd 100644 --- a/x/gravity/keeper/attestation.go +++ b/x/gravity/keeper/attestation.go @@ -1,21 +1,25 @@ package keeper import ( + "context" "fmt" "sort" "strconv" sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" + "cosmossdk.io/store/prefix" + storetypes "cosmossdk.io/store/types" "github.com/VolumeFi/whoops" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" + keeperutil "github.com/palomachain/paloma/util/keeper" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) func (k Keeper) Attest( - ctx sdk.Context, + ctx context.Context, claim types.EthereumClaim, anyClaim *codectypes.Any, ) (*types.Attestation, error) { @@ -27,7 +31,13 @@ func (k Keeper) Attest( return nil, fmt.Errorf("could not find ValAddr for delegate key, should be checked by now") } valAddr := val.GetOperator() - if err := sdk.VerifyAddressFormat(valAddr); err != nil { + + valAddress, err := keeperutil.ValAddressFromBech32(k.addressCodec, val.GetOperator()) + if err != nil { + return nil, err + } + + if err := sdk.VerifyAddressFormat(valAddress); err != nil { return nil, sdkerrors.Wrap(err, "invalid orchestrator validator address") } // Check that the nonce of this event is exactly one higher than the last nonce stored by this validator. @@ -36,7 +46,7 @@ func (k Keeper) Attest( // and prevents validators from submitting two claims with the same nonce. // This prevents there being two attestations with the same nonce that get 2/3s of the votes // in the endBlocker. - lastEventNonce, err := k.GetLastEventNonceByValidator(ctx, valAddr) + lastEventNonce, err := k.GetLastEventNonceByValidator(ctx, valAddress) if err != nil { return nil, err } @@ -50,13 +60,13 @@ func (k Keeper) Attest( return nil, sdkerrors.Wrap(err, "unable to compute claim hash") } att := k.GetAttestation(ctx, claim.GetEventNonce(), hash) - + sdkCtx := sdk.UnwrapSDKContext(ctx) // If it does not exist, create a new one. if att == nil { att = &types.Attestation{ Observed: false, Votes: []string{}, - Height: uint64(ctx.BlockHeight()), + Height: uint64(sdkCtx.BlockHeight()), Claim: anyClaim, } } @@ -69,10 +79,10 @@ func (k Keeper) Attest( if ethClaim.GetEthBlockHeight() == claim.GetEthBlockHeight() { // Add the validator's vote to this attestation // TODO : Only do if it's not already there - att.Votes = append(att.Votes, valAddr.String()) + att.Votes = append(att.Votes, valAddr) k.SetAttestation(ctx, claim.GetEventNonce(), hash, att) - err = k.SetLastEventNonceByValidator(ctx, valAddr, claim.GetEventNonce()) + err = k.SetLastEventNonceByValidator(ctx, valAddress, claim.GetEventNonce()) if err != nil { return nil, err } @@ -86,7 +96,7 @@ func (k Keeper) Attest( // TryAttestation checks if an attestation has enough votes to be applied to the consensus state // and has not already been marked Observed, then calls processAttestation to actually apply it to the state, // and then marks it Observed and emits an event. -func (k Keeper) TryAttestation(ctx sdk.Context, att *types.Attestation) error { +func (k Keeper) TryAttestation(ctx context.Context, att *types.Attestation) error { claim, err := k.UnpackAttestationClaim(att) if err != nil { return fmt.Errorf("could not cast to claim") @@ -100,17 +110,24 @@ func (k Keeper) TryAttestation(ctx sdk.Context, att *types.Attestation) error { if !att.Observed { // Sum the current powers of all validators who have voted and see if it passes the current threshold // TODO: The different integer types and math here needs a careful review - totalPower := k.StakingKeeper.GetLastTotalPower(ctx) - requiredPower := types.AttestationVotesPowerThreshold.Mul(totalPower).Quo(sdk.NewInt(100)) - attestationPower := sdk.NewInt(0) + totalPower, err := k.StakingKeeper.GetLastTotalPower(ctx) + if err != nil { + return err + } + requiredPower := types.AttestationVotesPowerThreshold.Mul(totalPower).Quo(math.NewInt(100)) + attestationPower := math.NewInt(0) for _, validator := range att.Votes { - val, err := sdk.ValAddressFromBech32(validator) + + val, err := keeperutil.ValAddressFromBech32(k.addressCodec, validator) + if err != nil { + return err + } + validatorPower, err := k.StakingKeeper.GetLastValidatorPower(ctx, val) if err != nil { return err } - validatorPower := k.StakingKeeper.GetLastValidatorPower(ctx, val) // Add it to the attestation power's sum - attestationPower = attestationPower.Add(sdk.NewInt(validatorPower)) + attestationPower = attestationPower.Add(math.NewInt(validatorPower)) // If the power of all the validators that have voted on the attestation is higher or equal to the threshold, // process the attestation, set Observed to true, and break if attestationPower.GT(requiredPower) { @@ -157,22 +174,22 @@ func (k Keeper) TryAttestation(ctx sdk.Context, att *types.Attestation) error { } // processAttestation actually applies the attestation to the consensus state -func (k Keeper) processAttestation(ctx sdk.Context, att *types.Attestation, claim types.EthereumClaim) error { +func (k Keeper) processAttestation(ctx context.Context, att *types.Attestation, claim types.EthereumClaim) error { hash, err := claim.ClaimHash() if err != nil { return fmt.Errorf("unable to compute claim hash") } + sdkCtx := sdk.UnwrapSDKContext(ctx) // then execute in a new Tx so that we can store state on failure - xCtx, commit := ctx.CacheContext() + xCtx, commit := sdkCtx.CacheContext() if err := k.AttestationHandler.Handle(xCtx, *att, claim); err != nil { // execute with a transient storage // If the attestation fails, something has gone wrong and we can't recover it. Log and move on // The attestation will still be marked "Observed", allowing the oracle to progress properly - k.Logger(ctx).Error("attestation failed", + liblog.FromSDKLogger(k.Logger(ctx)).WithFields( "cause", err.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("attestation failed") } else { commit() // persist transient storage } @@ -181,7 +198,7 @@ func (k Keeper) processAttestation(ctx sdk.Context, att *types.Attestation, clai // emitObservedEvent emits an event with information about an attestation that has been applied to // consensus state. -func (k Keeper) emitObservedEvent(ctx sdk.Context, att *types.Attestation, claim types.EthereumClaim) error { +func (k Keeper) emitObservedEvent(ctx context.Context, att *types.Attestation, claim types.EthereumClaim) error { hash, err := claim.ClaimHash() if err != nil { return sdkerrors.Wrap(err, "unable to compute claim hash") @@ -191,8 +208,8 @@ func (k Keeper) emitObservedEvent(ctx sdk.Context, att *types.Attestation, claim if err != nil { return err } - - return ctx.EventManager().EmitTypedEvent( + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.EventManager().EmitTypedEvent( &types.EventObservation{ AttestationType: string(claim.GetType()), BridgeContract: bridgeContract.GetAddress().Hex(), @@ -204,14 +221,14 @@ func (k Keeper) emitObservedEvent(ctx sdk.Context, att *types.Attestation, claim } // SetAttestation sets the attestation in the store -func (k Keeper) SetAttestation(ctx sdk.Context, eventNonce uint64, claimHash []byte, att *types.Attestation) { +func (k Keeper) SetAttestation(ctx context.Context, eventNonce uint64, claimHash []byte, att *types.Attestation) { store := k.GetStore(ctx) aKey := types.GetAttestationKey(eventNonce, claimHash) store.Set(aKey, k.cdc.MustMarshal(att)) } // GetAttestation return an attestation given a nonce -func (k Keeper) GetAttestation(ctx sdk.Context, eventNonce uint64, claimHash []byte) *types.Attestation { +func (k Keeper) GetAttestation(ctx context.Context, eventNonce uint64, claimHash []byte) *types.Attestation { store := k.GetStore(ctx) aKey := types.GetAttestationKey(eventNonce, claimHash) bz := store.Get(aKey) @@ -224,7 +241,7 @@ func (k Keeper) GetAttestation(ctx sdk.Context, eventNonce uint64, claimHash []b } // DeleteAttestation deletes the given attestation -func (k Keeper) DeleteAttestation(ctx sdk.Context, att types.Attestation) error { +func (k Keeper) DeleteAttestation(ctx context.Context, att types.Attestation) error { claim, err := k.UnpackAttestationClaim(&att) if err != nil { return fmt.Errorf("bad attestation in DeleteAttestation") @@ -243,7 +260,7 @@ func (k Keeper) DeleteAttestation(ctx sdk.Context, att types.Attestation) error // it also returns a pre-sorted array of the keys, this assists callers of this function // by providing a deterministic iteration order. You should always iterate over ordered keys // if you are iterating this map at all. -func (k Keeper) GetAttestationMapping(ctx sdk.Context) (attestationMapping map[uint64][]types.Attestation, orderedKeys []uint64, err error) { +func (k Keeper) GetAttestationMapping(ctx context.Context) (attestationMapping map[uint64][]types.Attestation, orderedKeys []uint64, err error) { attestationMapping = make(map[uint64][]types.Attestation) var g whoops.Group g.Add( @@ -277,7 +294,7 @@ func (k Keeper) GetAttestationMapping(ctx sdk.Context) (attestationMapping map[u // IterateAttestations iterates through all attestations executing a given callback on each discovered attestation // If reverse is true, attestations will be returned in descending order by key (aka by event nonce and then claim hash) // cb should return true to stop iteration, false to continue -func (k Keeper) IterateAttestations(ctx sdk.Context, reverse bool, cb func(key []byte, att types.Attestation) (stop bool)) error { +func (k Keeper) IterateAttestations(ctx context.Context, reverse bool, cb func(key []byte, att types.Attestation) (stop bool)) error { store := k.GetStore(ctx) keyPrefix := types.OracleAttestationKey start, end, err := prefixRange(keyPrefix) @@ -323,7 +340,7 @@ func (k Keeper) IterateAttestations(ctx sdk.Context, reverse bool, cb func(key [ // IterateClaims iterates through all attestations, filtering them for claims of a given type // If reverse is true, attestations will be returned in descending order by key (aka by event nonce and then claim hash) // cb should return true to stop iteration, false to continue -func (k Keeper) IterateClaims(ctx sdk.Context, reverse bool, claimType types.ClaimType, cb func(key []byte, att types.Attestation, claim types.EthereumClaim) (stop bool)) error { +func (k Keeper) IterateClaims(ctx context.Context, reverse bool, claimType types.ClaimType, cb func(key []byte, att types.Attestation, claim types.EthereumClaim) (stop bool)) error { typeUrl := types.ClaimTypeToTypeUrl(claimType) // Used to avoid unpacking undesired attestations var g whoops.Group @@ -350,7 +367,7 @@ func (k Keeper) IterateClaims(ctx sdk.Context, reverse bool, claimType types.Cla // GetMostRecentAttestations returns sorted (by nonce) attestations up to a provided limit number of attestations // Note: calls GetAttestationMapping in the hopes that there are potentially many attestations // which are distributed between few nonces to minimize sorting time -func (k Keeper) GetMostRecentAttestations(ctx sdk.Context, limit uint64) ([]types.Attestation, error) { +func (k Keeper) GetMostRecentAttestations(ctx context.Context, limit uint64) ([]types.Attestation, error) { attestationMapping, keys, err := k.GetAttestationMapping(ctx) if err != nil { return nil, err @@ -376,7 +393,7 @@ func (k Keeper) GetMostRecentAttestations(ctx sdk.Context, limit uint64) ([]type } // GetLastObservedEventNonce returns the latest observed event nonce -func (k Keeper) GetLastObservedEventNonce(ctx sdk.Context) (uint64, error) { +func (k Keeper) GetLastObservedEventNonce(ctx context.Context) (uint64, error) { store := k.GetStore(ctx) bytes := store.Get(types.LastObservedEventNonceKey) @@ -391,7 +408,7 @@ func (k Keeper) GetLastObservedEventNonce(ctx sdk.Context) (uint64, error) { // GetLastObservedEthereumBlockHeight height gets the block height to of the last observed attestation from // the store -func (k Keeper) GetLastObservedEthereumBlockHeight(ctx sdk.Context) types.LastObservedEthereumBlockHeight { +func (k Keeper) GetLastObservedEthereumBlockHeight(ctx context.Context) types.LastObservedEthereumBlockHeight { store := k.GetStore(ctx) bytes := store.Get(types.LastObservedEthereumBlockHeightKey) @@ -410,22 +427,23 @@ func (k Keeper) GetLastObservedEthereumBlockHeight(ctx sdk.Context) types.LastOb } // SetLastObservedEthereumBlockHeight sets the block height in the store. -func (k Keeper) SetLastObservedEthereumBlockHeight(ctx sdk.Context, ethereumHeight uint64) error { +func (k Keeper) SetLastObservedEthereumBlockHeight(ctx context.Context, ethereumHeight uint64) error { store := k.GetStore(ctx) previous := k.GetLastObservedEthereumBlockHeight(ctx) if previous.EthereumBlockHeight > ethereumHeight { return fmt.Errorf("attempt to roll back Ethereum block height") } + sdkCtx := sdk.UnwrapSDKContext(ctx) height := types.LastObservedEthereumBlockHeight{ EthereumBlockHeight: ethereumHeight, - PalomaBlockHeight: uint64(ctx.BlockHeight()), + PalomaBlockHeight: uint64(sdkCtx.BlockHeight()), } store.Set(types.LastObservedEthereumBlockHeightKey, k.cdc.MustMarshal(&height)) return nil } // setLastObservedEventNonce sets the latest observed event nonce -func (k Keeper) setLastObservedEventNonce(ctx sdk.Context, nonce uint64) error { +func (k Keeper) setLastObservedEventNonce(ctx context.Context, nonce uint64) error { store := k.GetStore(ctx) last, err := k.GetLastObservedEventNonce(ctx) if err != nil { @@ -442,7 +460,7 @@ func (k Keeper) setLastObservedEventNonce(ctx sdk.Context, nonce uint64) error { } // GetLastEventNonceByValidator returns the latest event nonce for a given validator -func (k Keeper) GetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress) (uint64, error) { +func (k Keeper) GetLastEventNonceByValidator(ctx context.Context, validator sdk.ValAddress) (uint64, error) { if err := sdk.VerifyAddressFormat(validator); err != nil { return 0, sdkerrors.Wrap(err, "invalid validator address") } @@ -472,7 +490,7 @@ func (k Keeper) GetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValA } // SetLastEventNonceByValidator sets the latest event nonce for a give validator -func (k Keeper) SetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValAddress, nonce uint64) error { +func (k Keeper) SetLastEventNonceByValidator(ctx context.Context, validator sdk.ValAddress, nonce uint64) error { if err := sdk.VerifyAddressFormat(validator); err != nil { return sdkerrors.Wrap(err, "invalid validator address") } @@ -486,7 +504,7 @@ func (k Keeper) SetLastEventNonceByValidator(ctx sdk.Context, validator sdk.ValA } // IterateValidatorLastEventNonces iterates through all batch confirmations -func (k Keeper) IterateValidatorLastEventNonces(ctx sdk.Context, cb func(key []byte, nonce uint64) (stop bool)) error { +func (k Keeper) IterateValidatorLastEventNonces(ctx context.Context, cb func(key []byte, nonce uint64) (stop bool)) error { store := k.GetStore(ctx) prefixStore := prefix.NewStore(store, types.LastEventNonceByValidatorKey) iter := prefixStore.Iterator(nil, nil) diff --git a/x/gravity/keeper/attestation_handler.go b/x/gravity/keeper/attestation_handler.go index d83ce177..51407305 100644 --- a/x/gravity/keeper/attestation_handler.go +++ b/x/gravity/keeper/attestation_handler.go @@ -1,12 +1,15 @@ package keeper import ( + "context" "fmt" "strconv" + sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) @@ -28,7 +31,7 @@ func (a AttestationHandler) ValidateMembers() { // Handle is the entry point for Attestation processing, only attestations with sufficient validator submissions // should be processed through this function, solidifying their effect in chain state -func (a AttestationHandler) Handle(ctx sdk.Context, att types.Attestation, claim types.EthereumClaim) error { +func (a AttestationHandler) Handle(ctx context.Context, att types.Attestation, claim types.EthereumClaim) error { switch claim := claim.(type) { case *types.MsgSendToPalomaClaim: @@ -45,7 +48,7 @@ func (a AttestationHandler) Handle(ctx sdk.Context, att types.Attestation, claim // Upon acceptance of sufficient validator SendToPaloma claims: transfer tokens to the appropriate paloma account // The paloma receiver must be a native account (e.g. paloma1abc...) // Bank module handles the transfer -func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgSendToPalomaClaim) error { +func (a AttestationHandler) handleSendToPaloma(ctx context.Context, claim types.MsgSendToPalomaClaim) error { invalidAddress := false // Validate the receiver as a valid bech32 address receiverAddress, addressErr := types.IBCAddressFromBech32(claim.PalomaReceiver) @@ -57,13 +60,12 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS return sdkerrors.Wrapf(er, "Unable to log error %v, could not compute ClaimHash for claim %v: %v", addressErr, claim, er) } - a.keeper.Logger(ctx).Error("Invalid SendToPaloma receiver", + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( "address", receiverAddress, "cause", addressErr.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("Invalid SendToPaloma receiver") } tokenAddress, errTokenAddress := types.NewEthAddress(claim.TokenContract) _, errEthereumSender := types.NewEthAddress(claim.EthereumSender) @@ -75,12 +77,11 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS if er != nil { return sdkerrors.Wrapf(er, "Unable to log error %v, could not compute ClaimHash for claim %v: %v", errTokenAddress, claim, er) } - a.keeper.Logger(ctx).Error("Invalid token contract", + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( "cause", errTokenAddress.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("Invalid token contract") return sdkerrors.Wrap(errTokenAddress, "invalid token contract on claim") } // likewise nil sender would have to be caused by a bogus event @@ -89,12 +90,11 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS if er != nil { return sdkerrors.Wrapf(er, "Unable to log error %v, could not compute ClaimHash for claim %v: %v", errEthereumSender, claim, er) } - a.keeper.Logger(ctx).Error("Invalid ethereum sender", + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( "cause", errEthereumSender.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("Invalid ethereum sender") return sdkerrors.Wrap(errTokenAddress, "invalid ethereum sender on claim") } @@ -129,7 +129,7 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS invalidAddress = true } } - + sdkCtx := sdk.UnwrapSDKContext(ctx) // for whatever reason above, invalid string, etc this deposit is not valid // we can't send the tokens back on the Ethereum side, and if we don't put them somewhere on // the paloma side they will be lost an inaccessible even though they are locked in the bridge. @@ -140,16 +140,15 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS if er != nil { return sdkerrors.Wrapf(er, "Unable to log error %v, could not compute ClaimHash for claim %v: %v", err, claim, er) } - a.keeper.Logger(ctx).Error("Failed community pool send", + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( "cause", err.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("Failed community pool send") return sdkerrors.Wrap(err, "failed to send to Community pool") } - if err := ctx.EventManager().EmitTypedEvent( + if err := sdkCtx.EventManager().EmitTypedEvent( &types.EventInvalidSendToPalomaReceiver{ Amount: claim.Amount.String(), Nonce: strconv.Itoa(int(claim.GetEventNonce())), @@ -161,7 +160,8 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS } } else { - if err := ctx.EventManager().EmitTypedEvent( + + if err := sdkCtx.EventManager().EmitTypedEvent( &types.EventSendToPaloma{ Amount: claim.Amount.String(), Nonce: strconv.Itoa(int(claim.GetEventNonce())), @@ -178,7 +178,8 @@ func (a AttestationHandler) handleSendToPaloma(ctx sdk.Context, claim types.MsgS // Upon acceptance of sufficient validator BatchSendToEth claims: burn ethereum originated vouchers, invalidate pending // batches with lower claim.BatchNonce, and clean up state // Note: Previously SendToEth was referred to as a bridge "Withdrawal", as tokens are withdrawn from the gravity contract -func (a AttestationHandler) handleBatchSendToEth(ctx sdk.Context, claim types.MsgBatchSendToEthClaim) error { +func (a AttestationHandler) handleBatchSendToEth(ctx context.Context, claim types.MsgBatchSendToEthClaim) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) contract, err := types.NewEthAddress(claim.TokenContract) if err != nil { return sdkerrors.Wrap(err, "invalid token contract on batch") @@ -187,7 +188,7 @@ func (a AttestationHandler) handleBatchSendToEth(ctx sdk.Context, claim types.Ms if err != nil { return err } - err = ctx.EventManager().EmitTypedEvent( + err = sdkCtx.EventManager().EmitTypedEvent( &types.EventBatchSendToEthClaim{ Nonce: strconv.Itoa(int(claim.BatchNonce)), }, @@ -197,7 +198,7 @@ func (a AttestationHandler) handleBatchSendToEth(ctx sdk.Context, claim types.Ms } // assertNothingSent performs a runtime assertion that the actual sent amount of `denom` is zero -func (a AttestationHandler) assertNothingSent(ctx sdk.Context, moduleAddr sdk.AccAddress, preSendBalance sdk.Coin, denom string) error { +func (a AttestationHandler) assertNothingSent(ctx context.Context, moduleAddr sdk.AccAddress, preSendBalance sdk.Coin, denom string) error { postSendBalance := a.keeper.bankKeeper.GetBalance(ctx, moduleAddr, denom) if !preSendBalance.Equal(postSendBalance) { return fmt.Errorf( @@ -210,7 +211,7 @@ func (a AttestationHandler) assertNothingSent(ctx sdk.Context, moduleAddr sdk.Ac // assertSentAmount performs a runtime assertion that the actual sent amount of `denom` equals the MsgSendToPaloma // claim's amount to send -func (a AttestationHandler) assertSentAmount(ctx sdk.Context, moduleAddr sdk.AccAddress, preSendBalance sdk.Coin, denom string, amount sdk.Int) error { +func (a AttestationHandler) assertSentAmount(ctx context.Context, moduleAddr sdk.AccAddress, preSendBalance sdk.Coin, denom string, amount math.Int) error { postSendBalance := a.keeper.bankKeeper.GetBalance(ctx, moduleAddr, denom) if !preSendBalance.Sub(postSendBalance).Amount.Equal(amount) { return fmt.Errorf( @@ -224,8 +225,9 @@ func (a AttestationHandler) assertSentAmount(ctx sdk.Context, moduleAddr sdk.Acc // Send tokens via bank keeper to a native gravity address, re-prefixing receiver to a gravity native address if necessary // Note: This should only be used as part of SendToPaloma attestation handling and is not a good solution for general use func (a AttestationHandler) sendCoinToLocalAddress( - ctx sdk.Context, claim types.MsgSendToPalomaClaim, receiver sdk.AccAddress, coin sdk.Coin, + ctx context.Context, claim types.MsgSendToPalomaClaim, receiver sdk.AccAddress, coin sdk.Coin, ) (err error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) err = a.keeper.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, receiver, sdk.NewCoins(coin)) if err != nil { // log and send to Community pool @@ -233,19 +235,22 @@ func (a AttestationHandler) sendCoinToLocalAddress( if er != nil { return sdkerrors.Wrapf(er, "Unable to log error %v, could not compute ClaimHash for claim %v: %v", err, claim, er) } - a.keeper.Logger(ctx).Error("Failed deposit", + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( "cause", err.Error(), "claim type", claim.GetType(), "id", types.GetAttestationKey(claim.GetEventNonce(), hash), - "nonce", fmt.Sprint(claim.GetEventNonce()), - ) + "nonce", fmt.Sprint(claim.GetEventNonce())).Error("Failed deposit") } else { // no error - a.keeper.Logger(ctx).Info("SendToPaloma to local gravity receiver", "ethSender", claim.EthereumSender, - "receiver", receiver, "denom", coin.Denom, "amount", coin.Amount.String(), "nonce", claim.EventNonce, - "ethContract", claim.TokenContract, "ethBlockHeight", claim.EthBlockHeight, - "palomaBlockHeight", ctx.BlockHeight(), - ) - if err := ctx.EventManager().EmitTypedEvent(&types.EventSendToPalomaLocal{ + liblog.FromSDKLogger(a.keeper.Logger(ctx)).WithFields( + "ethSender", claim.EthereumSender, + "receiver", receiver, + "denom", coin.Denom, + "amount", coin.Amount.String(), + "nonce", claim.EventNonce, + "ethContract", claim.TokenContract, + "ethBlockHeight", claim.EthBlockHeight, + "palomaBlockHeight", sdkCtx.BlockHeight()).Info("SendToPaloma to local gravity receiver") + if err := sdkCtx.EventManager().EmitTypedEvent(&types.EventSendToPalomaLocal{ Nonce: fmt.Sprint(claim.EventNonce), Receiver: receiver.String(), Token: coin.Denom, diff --git a/x/gravity/keeper/attestation_test.go b/x/gravity/keeper/attestation_test.go index 46f262f1..a8ef2de8 100644 --- a/x/gravity/keeper/attestation_test.go +++ b/x/gravity/keeper/attestation_test.go @@ -4,6 +4,7 @@ import ( "bytes" "testing" + "cosmossdk.io/math" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdktypes "github.com/cosmos/cosmos-sdk/types" "github.com/ethereum/go-ethereum/common" @@ -95,7 +96,7 @@ func createAttestations(t *testing.T, length int, k Keeper, ctx sdktypes.Context EventNonce: nonce, EthBlockHeight: 1, TokenContract: contract, - Amount: sdktypes.NewInt(10000000000 + int64(i)), + Amount: math.NewInt(10000000000 + int64(i)), EthereumSender: sender, PalomaReceiver: receiver, Orchestrator: orch, @@ -203,7 +204,7 @@ func TestInvalidHeight(t *testing.T) { DestAddress: receiver.String(), Erc20Token: types.ERC20Token{ Contract: tokenContract, - Amount: sdktypes.NewInt(1), + Amount: math.NewInt(1), }, }}, TokenContract: tokenContract, diff --git a/x/gravity/keeper/batch.go b/x/gravity/keeper/batch.go index 957a574c..e7214935 100644 --- a/x/gravity/keeper/batch.go +++ b/x/gravity/keeper/batch.go @@ -1,13 +1,15 @@ package keeper import ( + "context" "fmt" "strconv" "time" sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" + "cosmossdk.io/store/prefix" "github.com/VolumeFi/whoops" - "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" ) @@ -20,11 +22,12 @@ const OutgoingTxBatchSize = 100 // - persist an outgoing batch object with an incrementing ID = nonce // - emit an event func (k Keeper) BuildOutgoingTXBatch( - ctx sdk.Context, + ctx context.Context, chainReferenceID string, contract types.EthAddress, maxElements uint, ) (*types.InternalOutgoingTxBatch, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) if maxElements == 0 { return nil, sdkerrors.Wrap(types.ErrInvalid, "max elements value") } @@ -57,7 +60,7 @@ func (k Keeper) BuildOutgoingTXBatch( return nil, sdkerrors.Wrap(err, "unable to create batch") } // set the current block height when storing the batch - batch.PalomaBlockCreated = uint64(ctx.BlockHeight()) + batch.PalomaBlockCreated = uint64(sdkCtx.BlockHeight()) err = k.StoreBatch(ctx, *batch) if err != nil { return nil, err @@ -74,7 +77,7 @@ func (k Keeper) BuildOutgoingTXBatch( return nil, err } - return batch, ctx.EventManager().EmitTypedEvent( + return batch, sdkCtx.EventManager().EmitTypedEvent( &types.EventOutgoingBatch{ BridgeContract: bridgeContract.GetAddress().Hex(), BridgeChainId: strconv.Itoa(int(k.GetBridgeChainID(ctx))), @@ -85,13 +88,14 @@ func (k Keeper) BuildOutgoingTXBatch( ) } -func (k Keeper) getBatchTimeoutHeight(ctx sdk.Context) uint64 { - return uint64(ctx.BlockTime().Add(10 * time.Minute).Unix()) +func (k Keeper) getBatchTimeoutHeight(ctx context.Context) uint64 { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return uint64(sdkCtx.BlockTime().Add(10 * time.Minute).Unix()) } // OutgoingTxBatchExecuted is run when the Cosmos chain detects that a batch has been executed on Ethereum // It frees all the transactions in the batch -func (k Keeper) OutgoingTxBatchExecuted(ctx sdk.Context, tokenContract types.EthAddress, claim types.MsgBatchSendToEthClaim) error { +func (k Keeper) OutgoingTxBatchExecuted(ctx context.Context, tokenContract types.EthAddress, claim types.MsgBatchSendToEthClaim) error { b, err := k.GetOutgoingTXBatch(ctx, tokenContract, claim.BatchNonce) if err != nil { return err @@ -103,7 +107,7 @@ func (k Keeper) OutgoingTxBatchExecuted(ctx sdk.Context, tokenContract types.Eth return fmt.Errorf("Batch with nonce %d submitted after it timed out (submission %d >= timeout %d)?", claim.BatchNonce, claim.EthBlockHeight, b.BatchTimeout) } - totalToBurn := sdk.NewInt(0) + totalToBurn := math.NewInt(0) for _, tx := range b.Transactions { totalToBurn = totalToBurn.Add(tx.Erc20Token.Amount) } @@ -130,7 +134,7 @@ func (k Keeper) OutgoingTxBatchExecuted(ctx sdk.Context, tokenContract types.Eth // StoreBatch stores a transaction batch, it will refuse to overwrite an existing // batch and errors instead, once a batch is stored in state signature collection begins // so no mutation of a batch in state can ever be valid -func (k Keeper) StoreBatch(ctx sdk.Context, batch types.InternalOutgoingTxBatch) error { +func (k Keeper) StoreBatch(ctx context.Context, batch types.InternalOutgoingTxBatch) error { if err := batch.ValidateBasic(); err != nil { return sdkerrors.Wrap(err, "attempted to store invalid batch") } @@ -145,7 +149,7 @@ func (k Keeper) StoreBatch(ctx sdk.Context, batch types.InternalOutgoingTxBatch) } // DeleteBatch deletes an outgoing transaction batch -func (k Keeper) DeleteBatch(ctx sdk.Context, batch types.InternalOutgoingTxBatch) error { +func (k Keeper) DeleteBatch(ctx context.Context, batch types.InternalOutgoingTxBatch) error { if err := batch.ValidateBasic(); err != nil { return sdkerrors.Wrap(err, "attempted to delete invalid batch") } @@ -157,7 +161,7 @@ func (k Keeper) DeleteBatch(ctx sdk.Context, batch types.InternalOutgoingTxBatch // pickUnbatchedTxs moves unbatched Txs from the pool into a collection ready for batching func (k Keeper) pickUnbatchedTxs( - ctx sdk.Context, + ctx context.Context, contractAddress types.EthAddress, maxElements uint, ) ([]*types.InternalOutgoingTransferTx, error) { @@ -194,7 +198,7 @@ func (k Keeper) pickUnbatchedTxs( } // GetOutgoingTXBatch loads a batch object. Returns nil when not exists. -func (k Keeper) GetOutgoingTXBatch(ctx sdk.Context, tokenContract types.EthAddress, nonce uint64) (*types.InternalOutgoingTxBatch, error) { +func (k Keeper) GetOutgoingTXBatch(ctx context.Context, tokenContract types.EthAddress, nonce uint64) (*types.InternalOutgoingTxBatch, error) { store := k.GetStore(ctx) key := types.GetOutgoingTxBatchKey(tokenContract, nonce) bz := store.Get(key) @@ -214,7 +218,7 @@ func (k Keeper) GetOutgoingTXBatch(ctx sdk.Context, tokenContract types.EthAddre } // CancelOutgoingTXBatch releases all TX in the batch and deletes the batch -func (k Keeper) CancelOutgoingTXBatch(ctx sdk.Context, tokenContract types.EthAddress, nonce uint64) error { +func (k Keeper) CancelOutgoingTXBatch(ctx context.Context, tokenContract types.EthAddress, nonce uint64) error { batch, err := k.GetOutgoingTXBatch(ctx, tokenContract, nonce) if err != nil { return err @@ -245,8 +249,8 @@ func (k Keeper) CancelOutgoingTXBatch(ctx sdk.Context, tokenContract types.EthAd if err != nil { return err } - - return ctx.EventManager().EmitTypedEvent( + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.EventManager().EmitTypedEvent( &types.EventOutgoingBatchCanceled{ BridgeContract: bridgeContract.GetAddress().Hex(), BridgeChainId: strconv.Itoa(int(k.GetBridgeChainID(ctx))), @@ -257,7 +261,7 @@ func (k Keeper) CancelOutgoingTXBatch(ctx sdk.Context, tokenContract types.EthAd } // IterateOutgoingTxBatches iterates through all outgoing batches in ASC order. -func (k Keeper) IterateOutgoingTxBatches(ctx sdk.Context, cb func(key []byte, batch types.InternalOutgoingTxBatch) bool) error { +func (k Keeper) IterateOutgoingTxBatches(ctx context.Context, cb func(key []byte, batch types.InternalOutgoingTxBatch) bool) error { prefixStore := prefix.NewStore(k.GetStore(ctx), types.OutgoingTXBatchKey) iter := prefixStore.ReverseIterator(nil, nil) defer iter.Close() @@ -277,7 +281,7 @@ func (k Keeper) IterateOutgoingTxBatches(ctx sdk.Context, cb func(key []byte, ba } // GetOutgoingTxBatches returns the outgoing tx batches -func (k Keeper) GetOutgoingTxBatches(ctx sdk.Context) (out []types.InternalOutgoingTxBatch, err error) { +func (k Keeper) GetOutgoingTxBatches(ctx context.Context) (out []types.InternalOutgoingTxBatch, err error) { err = k.IterateOutgoingTxBatches(ctx, func(_ []byte, batch types.InternalOutgoingTxBatch) bool { out = append(out, batch) return false @@ -285,7 +289,7 @@ func (k Keeper) GetOutgoingTxBatches(ctx sdk.Context) (out []types.InternalOutgo return } -func (k Keeper) GetOutgoingTxBatchesByNonce(ctx sdk.Context) (map[uint64]types.InternalOutgoingTxBatch, error) { +func (k Keeper) GetOutgoingTxBatchesByNonce(ctx context.Context) (map[uint64]types.InternalOutgoingTxBatch, error) { batchesByNonce := make(map[uint64]types.InternalOutgoingTxBatch) var g whoops.Group g.Add( @@ -305,7 +309,7 @@ func (k Keeper) GetOutgoingTxBatchesByNonce(ctx sdk.Context) (map[uint64]types.I } // GetLastOutgoingBatchByTokenType gets the latest outgoing tx batch by token type -func (k Keeper) GetLastOutgoingBatchByTokenType(ctx sdk.Context, token types.EthAddress) (*types.InternalOutgoingTxBatch, error) { +func (k Keeper) GetLastOutgoingBatchByTokenType(ctx context.Context, token types.EthAddress) (*types.InternalOutgoingTxBatch, error) { batches, err := k.GetOutgoingTxBatches(ctx) if err != nil { return nil, err @@ -322,14 +326,14 @@ func (k Keeper) GetLastOutgoingBatchByTokenType(ctx sdk.Context, token types.Eth } // HasLastSlashedBatchBlock returns true if the last slashed batch block has been set in the store -func (k Keeper) HasLastSlashedBatchBlock(ctx sdk.Context) bool { +func (k Keeper) HasLastSlashedBatchBlock(ctx context.Context) bool { store := k.GetStore(ctx) return store.Has(types.LastSlashedBatchBlock) } // SetLastSlashedBatchBlock sets the latest slashed Batch block height this is done by // block height instead of nonce because batches could have individual nonces for each token type -func (k Keeper) SetLastSlashedBatchBlock(ctx sdk.Context, blockHeight uint64) error { +func (k Keeper) SetLastSlashedBatchBlock(ctx context.Context, blockHeight uint64) error { if k.HasLastSlashedBatchBlock(ctx) { lastSlashedBatchBlock, err := k.GetLastSlashedBatchBlock(ctx) if err != nil { @@ -346,7 +350,7 @@ func (k Keeper) SetLastSlashedBatchBlock(ctx sdk.Context, blockHeight uint64) er } // GetLastSlashedBatchBlock returns the latest slashed Batch block -func (k Keeper) GetLastSlashedBatchBlock(ctx sdk.Context) (uint64, error) { +func (k Keeper) GetLastSlashedBatchBlock(ctx context.Context) (uint64, error) { store := k.GetStore(ctx) bytes := store.Get(types.LastSlashedBatchBlock) @@ -357,7 +361,7 @@ func (k Keeper) GetLastSlashedBatchBlock(ctx sdk.Context) (uint64, error) { } // GetUnSlashedBatches returns all the unslashed batches in state -func (k Keeper) GetUnSlashedBatches(ctx sdk.Context, maxHeight uint64) (out []types.InternalOutgoingTxBatch, err error) { +func (k Keeper) GetUnSlashedBatches(ctx context.Context, maxHeight uint64) (out []types.InternalOutgoingTxBatch, err error) { lastSlashedBatchBlock, err := k.GetLastSlashedBatchBlock(ctx) if err != nil { return nil, err diff --git a/x/gravity/keeper/batch_test.go b/x/gravity/keeper/batch_test.go index df5927d6..612ccf14 100644 --- a/x/gravity/keeper/batch_test.go +++ b/x/gravity/keeper/batch_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" vtypes "github.com/palomachain/paloma/x/valset/types" @@ -23,7 +24,7 @@ func TestBatches(t *testing.T) { mySender, e1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") myReceiver, e2 = types.NewEthAddress("0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7") myTokenContractAddr, e3 = types.NewEthAddress(testERC20Address) - token, e4 = types.NewInternalERC20Token(sdk.NewInt(99999), myTokenContractAddr.GetAddress().Hex(), "test-chain") + token, e4 = types.NewInternalERC20Token(math.NewInt(99999), myTokenContractAddr.GetAddress().Hex(), "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) require.NoError(t, e1) @@ -47,7 +48,7 @@ func TestBatches(t *testing.T) { // add some TX to the pool for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), myTokenContractAddr.GetAddress().Hex(), "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -138,9 +139,9 @@ func TestBatches(t *testing.T) { gotUnbatchedTx, err := input.GravityKeeper.GetUnbatchedTransactionsByContract(ctx, *myTokenContractAddr) require.NoError(t, err) - oneHundredTok, err := types.NewInternalERC20Token(sdk.NewInt(100), myTokenContractAddr.GetAddress().Hex(), "test-chain") + oneHundredTok, err := types.NewInternalERC20Token(math.NewInt(100), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) - oneHundredOneTok, err := types.NewInternalERC20Token(sdk.NewInt(101), myTokenContractAddr.GetAddress().Hex(), "test-chain") + oneHundredOneTok, err := types.NewInternalERC20Token(math.NewInt(101), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) // and verify remaining available Tx in the pool @@ -276,8 +277,8 @@ func TestBatchesFullCoins(t *testing.T) { mySender, e1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") myReceiver = "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7" receiverAddr, e2 = types.NewEthAddress(myReceiver) - totalCoins, _ = sdk.NewIntFromString("1500000000000000000000") // 1,500 ETH worth - oneEth, _ = sdk.NewIntFromString("1000000000000000000") + totalCoins, _ = math.NewIntFromString("1500000000000000000000") // 1,500 ETH worth + oneEth, _ = math.NewIntFromString("1000000000000000000") token, e3 = types.NewInternalERC20Token(totalCoins, testERC20Address, "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) @@ -298,7 +299,7 @@ func TestBatchesFullCoins(t *testing.T) { // add some TX to the pool for _, v := range []uint64{20, 300, 25, 10} { - vAsSDKInt := sdk.NewIntFromUint64(v) + vAsSDKInt := math.NewIntFromUint64(v) amountToken, err := types.NewInternalERC20Token(oneEth.Mul(vAsSDKInt), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -326,13 +327,13 @@ func TestBatchesFullCoins(t *testing.T) { Id: 2, Sender: mySender.String(), DestAddress: myReceiver, - Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(sdk.NewIntFromUint64(300)), testERC20Address, "test-chain"), + Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(math.NewIntFromUint64(300)), testERC20Address, "test-chain"), }, { Id: 3, Sender: mySender.String(), DestAddress: myReceiver, - Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(sdk.NewIntFromUint64(25)), testERC20Address, "test-chain"), + Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(math.NewIntFromUint64(25)), testERC20Address, "test-chain"), }, }, TokenContract: testERC20Address, @@ -350,9 +351,9 @@ func TestBatchesFullCoins(t *testing.T) { // and verify remaining available Tx in the pool gotUnbatchedTx, err := input.GravityKeeper.GetUnbatchedTransactionsByContract(ctx, *tokenContract) require.NoError(t, err) - twentyTok, err := types.NewInternalERC20Token(oneEth.Mul(sdk.NewIntFromUint64(20)), testERC20Address, "test-chain") + twentyTok, err := types.NewInternalERC20Token(oneEth.Mul(math.NewIntFromUint64(20)), testERC20Address, "test-chain") require.NoError(t, err) - tenTok, err := types.NewInternalERC20Token(oneEth.Mul(sdk.NewIntFromUint64(10)), testERC20Address, "test-chain") + tenTok, err := types.NewInternalERC20Token(oneEth.Mul(math.NewIntFromUint64(10)), testERC20Address, "test-chain") require.NoError(t, err) expUnbatchedTx := []*types.InternalOutgoingTransferTx{ { @@ -375,7 +376,7 @@ func TestBatchesFullCoins(t *testing.T) { // add some more TX to the pool to create a more profitable batch for _, v := range []uint64{200, 150} { - vAsSDKInt := sdk.NewIntFromUint64(v) + vAsSDKInt := math.NewIntFromUint64(v) amountToken, err := types.NewInternalERC20Token(oneEth.Mul(vAsSDKInt), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -399,13 +400,13 @@ func TestBatchesFullCoins(t *testing.T) { Id: 5, Sender: mySender.String(), DestAddress: myReceiver, - Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(sdk.NewIntFromUint64(200)), testERC20Address, "test-chain"), + Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(math.NewIntFromUint64(200)), testERC20Address, "test-chain"), }, { Id: 6, Sender: mySender.String(), DestAddress: myReceiver, - Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(sdk.NewIntFromUint64(150)), testERC20Address, "test-chain"), + Erc20Token: types.NewSDKIntERC20Token(oneEth.Mul(math.NewIntFromUint64(150)), testERC20Address, "test-chain"), }, }, TokenContract: testERC20Address, @@ -456,8 +457,8 @@ func TestBatchesFullCoins(t *testing.T) { // tokenContractAddr2 = "0xF815240800ddf3E0be80e0d848B13ecaa504BF37" // tokenContractAddr3 = "0xd086dDA7BccEB70e35064f540d07E4baED142cB3" // tokenContractAddr4 = "0x384981B9d133701c4bD445F77bF61C3d80e79D46" -// totalCoins, _ = sdk.NewIntFromString("1500000000000000000000000") -// oneEth, _ = sdk.NewIntFromString("1000000000000000000") +// totalCoins, _ = math.NewIntFromString("1500000000000000000000000") +// oneEth, _ = math.NewIntFromString("1000000000000000000") // token1, e2 = types.NewInternalERC20Token(totalCoins, tokenContractAddr1, "test-chain") // token2, e3 = types.NewInternalERC20Token(totalCoins, tokenContractAddr2, "test-chain") // token3, e4 = types.NewInternalERC20Token(totalCoins, tokenContractAddr3, "test-chain") @@ -492,7 +493,7 @@ func TestBatchesFullCoins(t *testing.T) { // contractAddr, err := types.NewEthAddress(contract) // require.NoError(t, err) // for v := 1; v < 500; v++ { -// vAsSDKInt := sdk.NewIntFromUint64(uint64(v)) +// vAsSDKInt := math.NewIntFromUint64(uint64(v)) // amountToken, err := types.NewInternalERC20Token(oneEth.Mul(vAsSDKInt), contract, "test-chain") // require.NoError(t, err) // amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -548,9 +549,9 @@ func TestBatchesFullCoins(t *testing.T) { // mySender, e1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") // notMySender, e2 = sdk.AccAddressFromBech32("gravity1add7f8wyertuus9r20284ej0asrs085c8ajr0y") // myReceiver = "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7" -// token, e3 = types.NewInternalERC20Token(sdk.NewInt(414), testERC20Address, "test-chain") +// token, e3 = types.NewInternalERC20Token(math.NewInt(414), testERC20Address, "test-chain") // allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) -// denomToken, e4 = types.NewInternalERC20Token(sdk.NewInt(1), testERC20Address, "test-chain") +// denomToken, e4 = types.NewInternalERC20Token(math.NewInt(1), testERC20Address, "test-chain") // myDenom = sdk.NewCoin(testDenom, denomToken.Amount).Denom // ) // require.NoError(t, e1) @@ -573,7 +574,7 @@ func TestBatchesFullCoins(t *testing.T) { // // // add some TX to the pool // for i := 0; i < 4; i++ { -// amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") +// amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") // require.NoError(t, err) // amount := sdk.NewCoin(testDenom, amountToken.Amount) // @@ -591,7 +592,7 @@ func TestBatchesFullCoins(t *testing.T) { // // // Check the balance at the start // balances := input.BankKeeper.GetAllBalances(ctx, mySender) -// require.Equal(t, sdk.NewInt(8), balances.AmountOf(myDenom)) +// require.Equal(t, math.NewInt(8), balances.AmountOf(myDenom)) // // // tx batch size is 2, so that some of them stay behind // // Should have 4: and 3: from above @@ -612,7 +613,7 @@ func TestBatchesFullCoins(t *testing.T) { // // // make sure refund was issued // balances = input.BankKeeper.GetAllBalances(ctx, mySender) -// require.Equal(t, sdk.NewInt(109), balances.AmountOf(myDenom)) +// require.Equal(t, math.NewInt(109), balances.AmountOf(myDenom)) //} func TestBatchConfirms(t *testing.T) { @@ -622,7 +623,7 @@ func TestBatchConfirms(t *testing.T) { mySender, e1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") myReceiver, e2 = types.NewEthAddress("0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7") myTokenContractAddr, e3 = types.NewEthAddress(testERC20Address) - token, e4 = types.NewInternalERC20Token(sdk.NewInt(1000000), myTokenContractAddr.GetAddress().Hex(), "test-chain") + token, e4 = types.NewInternalERC20Token(math.NewInt(1000000), myTokenContractAddr.GetAddress().Hex(), "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) require.NoError(t, e1) @@ -641,7 +642,7 @@ func TestBatchConfirms(t *testing.T) { // add batches with 1 tx to the pool for i := 1; i < 200; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), myTokenContractAddr.GetAddress().Hex(), "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) diff --git a/x/gravity/keeper/cosmos-originated.go b/x/gravity/keeper/cosmos-originated.go index a76d0c50..039fe0f4 100644 --- a/x/gravity/keeper/cosmos-originated.go +++ b/x/gravity/keeper/cosmos-originated.go @@ -1,16 +1,16 @@ package keeper import ( + "context" "errors" - "github.com/cosmos/cosmos-sdk/store/prefix" - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/store/prefix" keeperutil "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/x/gravity/types" ) -func (k Keeper) GetDenomOfERC20(ctx sdk.Context, chainReferenceId string, tokenContract types.EthAddress) (string, error) { - erc20ToDenom, err := keeperutil.Load[*types.ERC20ToDenom](k.GetStore(ctx), k.cdc, types.GetERC20ToDenomKey(chainReferenceId, tokenContract)) +func (k Keeper) GetDenomOfERC20(ctx context.Context, chainReferenceId string, tokenContract types.EthAddress) (string, error) { + erc20ToDenom, err := keeperutil.Load[*types.ERC20ToDenom](k.GetStore(ctx), k.ProtoUnmarshaler, types.GetERC20ToDenomKey(chainReferenceId, tokenContract)) if errors.Is(err, keeperutil.ErrNotFound) { return "", types.ErrDenomNotFound } @@ -22,8 +22,8 @@ func (k Keeper) GetDenomOfERC20(ctx sdk.Context, chainReferenceId string, tokenC return erc20ToDenom.Denom, nil } -func (k Keeper) GetERC20OfDenom(ctx sdk.Context, chainReferenceId, denom string) (*types.EthAddress, error) { - erc20ToDenom, err := keeperutil.Load[*types.ERC20ToDenom](k.GetStore(ctx), k.cdc, types.GetDenomToERC20Key(chainReferenceId, denom)) +func (k Keeper) GetERC20OfDenom(ctx context.Context, chainReferenceId, denom string) (*types.EthAddress, error) { + erc20ToDenom, err := keeperutil.Load[*types.ERC20ToDenom](k.GetStore(ctx), k.ProtoUnmarshaler, types.GetDenomToERC20Key(chainReferenceId, denom)) if errors.Is(err, keeperutil.ErrNotFound) { return nil, types.ErrERC20NotFound } @@ -40,7 +40,7 @@ func (k Keeper) GetERC20OfDenom(ctx sdk.Context, chainReferenceId, denom string) return ethAddr, nil } -func (k Keeper) GetAllERC20ToDenoms(ctx sdk.Context) ([]*types.ERC20ToDenom, error) { +func (k Keeper) GetAllERC20ToDenoms(ctx context.Context) ([]*types.ERC20ToDenom, error) { store := k.GetStore(ctx) prefixStore := prefix.NewStore(store, types.DenomToERC20Key) _, all, err := keeperutil.IterAll[*types.ERC20ToDenom](prefixStore, k.cdc) @@ -48,7 +48,7 @@ func (k Keeper) GetAllERC20ToDenoms(ctx sdk.Context) ([]*types.ERC20ToDenom, err return all, err } -func (k Keeper) setDenomToERC20(ctx sdk.Context, chainReferenceId, denom string, tokenContract types.EthAddress) error { +func (k Keeper) setDenomToERC20(ctx context.Context, chainReferenceId, denom string, tokenContract types.EthAddress) error { store := k.GetStore(ctx) denomToERC20 := types.ERC20ToDenom{ @@ -57,15 +57,15 @@ func (k Keeper) setDenomToERC20(ctx sdk.Context, chainReferenceId, denom string, Erc20: tokenContract.GetAddress().String(), } - err := keeperutil.Save(store, k.cdc, types.GetDenomToERC20Key(chainReferenceId, denom), &denomToERC20) + err := keeperutil.Save(store, k.Protomarshaler, types.GetDenomToERC20Key(chainReferenceId, denom), &denomToERC20) if err != nil { return err } - return keeperutil.Save(store, k.cdc, types.GetERC20ToDenomKey(chainReferenceId, tokenContract), &denomToERC20) + return keeperutil.Save(store, k.Protomarshaler, types.GetERC20ToDenomKey(chainReferenceId, tokenContract), &denomToERC20) } -func (k Keeper) GetAllDenomToERC20s(ctx sdk.Context) ([]*types.ERC20ToDenom, error) { +func (k Keeper) GetAllDenomToERC20s(ctx context.Context) ([]*types.ERC20ToDenom, error) { store := k.GetStore(ctx) prefixStore := prefix.NewStore(store, types.DenomToERC20Key) _, all, err := keeperutil.IterAll[*types.ERC20ToDenom](prefixStore, k.cdc) diff --git a/x/gravity/keeper/evidence.go b/x/gravity/keeper/evidence.go index 8e495784..34cc8728 100644 --- a/x/gravity/keeper/evidence.go +++ b/x/gravity/keeper/evidence.go @@ -2,17 +2,18 @@ package keeper import ( "bytes" + "context" "encoding/hex" "fmt" sdkerrors "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" + "cosmossdk.io/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" ) func (k Keeper) CheckBadSignatureEvidence( - ctx sdk.Context, + ctx context.Context, msg *types.MsgSubmitBadSignatureEvidence, chainReferenceID string, ) error { @@ -33,7 +34,7 @@ func (k Keeper) CheckBadSignatureEvidence( } } -func (k Keeper) checkBadSignatureEvidenceInternal(ctx sdk.Context, subject types.EthereumSigned, signature string) error { +func (k Keeper) checkBadSignatureEvidenceInternal(ctx context.Context, subject types.EthereumSigned, signature string) error { // Get checkpoint of the supposed bad signature (fake batch submitted to eth) ci, err := k.evmKeeper.GetChainInfo(ctx, subject.GetChainReferenceID()) @@ -82,11 +83,11 @@ func (k Keeper) checkBadSignatureEvidenceInternal(ctx sdk.Context, subject types if err != nil { return sdkerrors.Wrap(err, "Could not get consensus key address for validator") } - + sdkCtx := sdk.UnwrapSDKContext(ctx) params := k.GetParams(ctx) if !val.IsJailed() { k.StakingKeeper.Jail(ctx, cons) - k.StakingKeeper.Slash(ctx, cons, ctx.BlockHeight(), val.ConsensusPower(sdk.DefaultPowerReduction), params.SlashFractionBadEthSignature) + k.StakingKeeper.Slash(ctx, cons, sdkCtx.BlockHeight(), val.ConsensusPower(sdk.DefaultPowerReduction), params.SlashFractionBadEthSignature) } return nil @@ -94,13 +95,13 @@ func (k Keeper) checkBadSignatureEvidenceInternal(ctx sdk.Context, subject types // SetPastEthSignatureCheckpoint puts the checkpoint of a batch into a set // in order to prove later that it existed at one point. -func (k Keeper) SetPastEthSignatureCheckpoint(ctx sdk.Context, checkpoint []byte) { +func (k Keeper) SetPastEthSignatureCheckpoint(ctx context.Context, checkpoint []byte) { store := k.GetStore(ctx) store.Set(types.GetPastEthSignatureCheckpointKey(checkpoint), []byte{0x1}) } // GetPastEthSignatureCheckpoint tells you whether a given checkpoint has ever existed -func (k Keeper) GetPastEthSignatureCheckpoint(ctx sdk.Context, checkpoint []byte) (found bool) { +func (k Keeper) GetPastEthSignatureCheckpoint(ctx context.Context, checkpoint []byte) (found bool) { store := k.GetStore(ctx) if bytes.Equal(store.Get(types.GetPastEthSignatureCheckpointKey(checkpoint)), []byte{0x1}) { return true @@ -109,7 +110,7 @@ func (k Keeper) GetPastEthSignatureCheckpoint(ctx sdk.Context, checkpoint []byte } } -func (k Keeper) IteratePastEthSignatureCheckpoints(ctx sdk.Context, cb func(key []byte, value []byte) (stop bool)) error { +func (k Keeper) IteratePastEthSignatureCheckpoints(ctx context.Context, cb func(key []byte, value []byte) (stop bool)) error { prefixStore := prefix.NewStore(k.GetStore(ctx), types.PastEthSignatureCheckpointKey) iter := prefixStore.Iterator(nil, nil) defer iter.Close() diff --git a/x/gravity/keeper/evidence_test.go b/x/gravity/keeper/evidence_test.go index 857978d2..88388f81 100644 --- a/x/gravity/keeper/evidence_test.go +++ b/x/gravity/keeper/evidence_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" @@ -20,7 +21,7 @@ func TestSubmitBadSignatureEvidenceBatchExists(t *testing.T) { now = time.Now().UTC() mySender, e1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") myReceiver = "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7" - token, e2 = types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + token, e2 = types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) require.NoError(t, e1) @@ -40,7 +41,7 @@ func TestSubmitBadSignatureEvidenceBatchExists(t *testing.T) { // add some TX to the pool for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -95,6 +96,7 @@ func TestSubmitBadSignatureEvidenceSlash(t *testing.T) { err = input.GravityKeeper.CheckBadSignatureEvidence(ctx, &msg, "test-chain") require.NoError(t, err) - val := input.StakingKeeper.Validator(ctx, ValAddrs[0]) + val, err := input.StakingKeeper.Validator(ctx, ValAddrs[0]) + require.NoError(t, err) require.True(t, val.IsJailed()) } diff --git a/x/gravity/keeper/genesis.go b/x/gravity/keeper/genesis.go index 5445cf83..f884e519 100644 --- a/x/gravity/keeper/genesis.go +++ b/x/gravity/keeper/genesis.go @@ -1,6 +1,7 @@ package keeper import ( + "context" "fmt" sdkerrors "cosmossdk.io/errors" @@ -8,7 +9,7 @@ import ( "github.com/palomachain/paloma/x/gravity/types" ) -func initBridgeDataFromGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { +func initBridgeDataFromGenesis(ctx context.Context, k Keeper, data types.GenesisState) { // reset batches in state for _, batch := range data.Batches { // TODO: block height? @@ -33,7 +34,7 @@ func initBridgeDataFromGenesis(ctx sdk.Context, k Keeper, data types.GenesisStat } // InitGenesis starts a chain from a genesis state -func InitGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { +func InitGenesis(ctx context.Context, k Keeper, data types.GenesisState) { k.SetParams(ctx, *data.Params) // restore various nonces, this MUST match GravityNonces in genesis @@ -129,7 +130,7 @@ func InitGenesis(ctx sdk.Context, k Keeper, data types.GenesisState) { // ExportGenesis exports all the state needed to restart the chain // from the current state of the chain -func ExportGenesis(ctx sdk.Context, k Keeper) types.GenesisState { +func ExportGenesis(ctx context.Context, k Keeper) types.GenesisState { unbatchedTransfers, err := k.GetUnbatchedTransactions(ctx) if err != nil { panic(err) diff --git a/x/gravity/keeper/genesis_test.go b/x/gravity/keeper/genesis_test.go index 4a8a999c..d0056d5a 100644 --- a/x/gravity/keeper/genesis_test.go +++ b/x/gravity/keeper/genesis_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" "github.com/stretchr/testify/require" @@ -67,7 +68,7 @@ func TestBatchAndTxImportExport(t *testing.T) { tokens := make([]*types.InternalERC20Token, len(contracts)) vouchers := make([]*sdk.Coins, len(contracts)) for i, v := range contracts { - token, err := types.NewInternalERC20Token(sdk.NewInt(99999999), v.GetAddress().Hex(), "test-chain") + token, err := types.NewInternalERC20Token(math.NewInt(99999999), v.GetAddress().Hex(), "test-chain") tokens[i] = token allVouchers := sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) vouchers[i] = &allVouchers @@ -96,7 +97,7 @@ func TestBatchAndTxImportExport(t *testing.T) { sender := senders[i%len(senders)] receiver := receivers[i%len(receivers)] contract := contracts[i%len(contracts)] - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(amount)), contract.GetAddress().Hex(), "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(amount)), contract.GetAddress().Hex(), "test-chain") require.NoError(t, err) // add transaction to the pool diff --git a/x/gravity/keeper/grpc_query.go b/x/gravity/keeper/grpc_query.go index 61c585fe..160c1ddf 100644 --- a/x/gravity/keeper/grpc_query.go +++ b/x/gravity/keeper/grpc_query.go @@ -7,6 +7,7 @@ import ( "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + keeperutil "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/x/gravity/types" ) @@ -171,10 +172,11 @@ func (k Keeper) LastEventNonceByAddr( if !found { return nil, errors.Wrap(types.ErrUnknown, "address") } - if err := sdk.VerifyAddressFormat(validator.GetOperator()); err != nil { + valAddress, err := keeperutil.ValAddressFromBech32(k.addressCodec, validator.GetOperator()) + if err := sdk.VerifyAddressFormat(valAddress); err != nil { return nil, errors.Wrap(err, "invalid validator address") } - lastEventNonce, err := k.GetLastEventNonceByValidator(ctx, validator.GetOperator()) + lastEventNonce, err := k.GetLastEventNonceByValidator(ctx, valAddress) if err != nil { return nil, err } diff --git a/x/gravity/keeper/grpc_query_integration_test.go b/x/gravity/keeper/grpc_query_integration_test.go index 528f34e0..98bffc49 100644 --- a/x/gravity/keeper/grpc_query_integration_test.go +++ b/x/gravity/keeper/grpc_query_integration_test.go @@ -1,9 +1,11 @@ package keeper_test import ( + "context" gocontext "context" "testing" + "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/baseapp" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -15,16 +17,17 @@ import ( // nolint: exhaustruct func TestQueryGetAttestations(t *testing.T) { + input := keeper.CreateTestEnv(t) encCfg := app.MakeEncodingConfig() k := input.GravityKeeper ctx := input.Context - + sdkCtx := sdk.UnwrapSDKContext(ctx) // Some query functions use additional logic to determine if they should look up values using the v1 key, or the new // hashed bytes keys used post-Mercury, so we must set the block height high enough here for the correct data to be found - ctx = ctx.WithBlockHeight(int64(keeper.MERCURY_UPGRADE_HEIGHT) + ctx.BlockHeight()) + ctx = sdkCtx.WithBlockHeight(int64(keeper.MERCURY_UPGRADE_HEIGHT) + sdkCtx.BlockHeight()) - queryHelper := baseapp.NewQueryServerTestHelper(ctx, encCfg.InterfaceRegistry) + queryHelper := baseapp.NewQueryServerTestHelper(sdkCtx, encCfg.InterfaceRegistry) types.RegisterQueryServer(queryHelper, k) queryClient := types.NewQueryClient(queryHelper) @@ -128,7 +131,7 @@ func TestQueryGetAttestations(t *testing.T) { } } -func createAttestations(t *testing.T, k keeper.Keeper, ctx sdk.Context, length int) { +func createAttestations(t *testing.T, k keeper.Keeper, ctx context.Context, length int) { t.Helper() for i := 0; i < length; i++ { @@ -137,7 +140,7 @@ func createAttestations(t *testing.T, k keeper.Keeper, ctx sdk.Context, length i EventNonce: nonce, EthBlockHeight: 1, TokenContract: "0x00000000000000000001", - Amount: sdk.NewInt(10000000000 + int64(i)), + Amount: math.NewInt(10000000000 + int64(i)), EthereumSender: "0x00000000000000000002", PalomaReceiver: "0x00000000000000000003", Orchestrator: "0x00000000000000000004", @@ -145,11 +148,11 @@ func createAttestations(t *testing.T, k keeper.Keeper, ctx sdk.Context, length i any, err := codectypes.NewAnyWithValue(&msg) require.NoError(t, err) - + sdkCtx := sdk.UnwrapSDKContext(ctx) att := &types.Attestation{ Observed: false, Votes: []string{}, - Height: uint64(ctx.BlockHeight()), + Height: uint64(sdkCtx.BlockHeight()), Claim: any, } diff --git a/x/gravity/keeper/grpc_query_test.go b/x/gravity/keeper/grpc_query_test.go index beaf7908..c813d65b 100644 --- a/x/gravity/keeper/grpc_query_test.go +++ b/x/gravity/keeper/grpc_query_test.go @@ -5,6 +5,7 @@ import ( "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" vtypes "github.com/palomachain/paloma/x/valset/types" @@ -28,7 +29,7 @@ func TestLastPendingBatchRequest(t *testing.T) { Sender: "paloma1qyqszqgpqyqszqgpqyqszqgpqyqszqgp2kvale", DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(103), + Amount: math.NewInt(103), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -38,7 +39,7 @@ func TestLastPendingBatchRequest(t *testing.T) { Sender: "paloma1qyqszqgpqyqszqgpqyqszqgpqyqszqgp2kvale", DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(102), + Amount: math.NewInt(102), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -89,7 +90,7 @@ func createTestBatch(t *testing.T, input TestInput, maxTxElements uint) { tokenContract, err := types.NewEthAddress(testERC20Address) require.NoError(t, err) // mint some voucher first - token, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + token, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, token.Amount)} err = input.BankKeeper.MintCoins(input.Context, types.ModuleName, allVouchers) @@ -102,7 +103,7 @@ func createTestBatch(t *testing.T, input TestInput, maxTxElements uint) { // add some TX to the pool for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) _, err = input.GravityKeeper.AddToOutgoingPool(input.Context, mySender, *receiver, amount, "test-chain") @@ -192,7 +193,7 @@ func TestQueryBatch(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(103), + Amount: math.NewInt(103), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -202,7 +203,7 @@ func TestQueryBatch(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(102), + Amount: math.NewInt(102), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -245,7 +246,7 @@ func TestLastBatchesRequest(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(103), + Amount: math.NewInt(103), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -255,7 +256,7 @@ func TestLastBatchesRequest(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(102), + Amount: math.NewInt(102), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -265,7 +266,7 @@ func TestLastBatchesRequest(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(101), + Amount: math.NewInt(101), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -283,7 +284,7 @@ func TestLastBatchesRequest(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(103), + Amount: math.NewInt(103), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -293,7 +294,7 @@ func TestLastBatchesRequest(t *testing.T) { { DestAddress: "0x320915BD0F1bad11cBf06e85D5199DBcAC4E9934", Erc20Token: types.ERC20Token{ - Amount: sdk.NewInt(102), + Amount: math.NewInt(102), Contract: testERC20Address, ChainReferenceId: "test-chain", }, @@ -388,7 +389,7 @@ func TestQueryPendingSendToEth(t *testing.T) { now = time.Now().UTC() mySender, err1 = sdk.AccAddressFromBech32("paloma1ahx7f8wyertuus9r20284ej0asrs085c945jyk") myReceiver = "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7" - token, err2 = types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + token, err2 = types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") allVouchers = sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) ) require.NoError(t, err1) @@ -409,7 +410,7 @@ func TestQueryPendingSendToEth(t *testing.T) { // add some TX to the pool for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) _, err = input.GravityKeeper.AddToOutgoingPool(sdkCtx, mySender, *receiver, amount, "test-chain") @@ -440,7 +441,7 @@ func TestQueryPendingSendToEth(t *testing.T) { DestAddress: "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7", Erc20Token: types.ERC20Token{ Contract: testERC20Address, - Amount: sdk.NewInt(103), + Amount: math.NewInt(103), ChainReferenceId: "test-chain", }, }, @@ -450,7 +451,7 @@ func TestQueryPendingSendToEth(t *testing.T) { DestAddress: "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7", Erc20Token: types.ERC20Token{ Contract: testERC20Address, - Amount: sdk.NewInt(102), + Amount: math.NewInt(102), ChainReferenceId: "test-chain", }, }, @@ -463,7 +464,7 @@ func TestQueryPendingSendToEth(t *testing.T) { DestAddress: "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7", Erc20Token: types.ERC20Token{ Contract: testERC20Address, - Amount: sdk.NewInt(101), + Amount: math.NewInt(101), ChainReferenceId: "test-chain", }, }, @@ -473,7 +474,7 @@ func TestQueryPendingSendToEth(t *testing.T) { DestAddress: "0xd041c41EA1bf0F006ADBb6d2c9ef9D425dE5eaD7", Erc20Token: types.ERC20Token{ Contract: testERC20Address, - Amount: sdk.NewInt(100), + Amount: math.NewInt(100), ChainReferenceId: "test-chain", }, }, diff --git a/x/gravity/keeper/hooks.go b/x/gravity/keeper/hooks.go index 8b9f95c9..9acc50c8 100644 --- a/x/gravity/keeper/hooks.go +++ b/x/gravity/keeper/hooks.go @@ -1,6 +1,9 @@ package keeper import ( + "context" + + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) @@ -17,46 +20,46 @@ func (k Keeper) Hooks() Hooks { return Hooks{k} } -func (h Hooks) AfterUnbondingInitiated(ctx sdk.Context, id uint64) error { +func (h Hooks) AfterUnbondingInitiated(ctx context.Context, id uint64) error { return nil } -func (h Hooks) AfterValidatorBeginUnbonding(ctx sdk.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorBeginUnbonding(ctx context.Context, consAddr sdk.ConsAddress, valAddr sdk.ValAddress) error { return nil } -func (h Hooks) BeforeDelegationCreated(_ sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) BeforeDelegationCreated(_ context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { return nil } -func (h Hooks) AfterValidatorCreated(ctx sdk.Context, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorCreated(ctx context.Context, valAddr sdk.ValAddress) error { return nil } -func (h Hooks) BeforeValidatorModified(_ sdk.Context, _ sdk.ValAddress) error { +func (h Hooks) BeforeValidatorModified(_ context.Context, _ sdk.ValAddress) error { return nil } -func (h Hooks) AfterValidatorBonded(_ sdk.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { +func (h Hooks) AfterValidatorBonded(_ context.Context, _ sdk.ConsAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) BeforeDelegationRemoved(_ sdk.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { +func (h Hooks) BeforeDelegationRemoved(_ context.Context, _ sdk.AccAddress, _ sdk.ValAddress) error { return nil } -func (h Hooks) AfterValidatorRemoved(ctx sdk.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterValidatorRemoved(ctx context.Context, _ sdk.ConsAddress, valAddr sdk.ValAddress) error { return nil } -func (h Hooks) BeforeValidatorSlashed(ctx sdk.Context, valAddr sdk.ValAddress, fraction sdk.Dec) error { +func (h Hooks) BeforeValidatorSlashed(ctx context.Context, valAddr sdk.ValAddress, fraction math.LegacyDec) error { return nil } -func (h Hooks) BeforeDelegationSharesModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) BeforeDelegationSharesModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { return nil } -func (h Hooks) AfterDelegationModified(ctx sdk.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { +func (h Hooks) AfterDelegationModified(ctx context.Context, delAddr sdk.AccAddress, valAddr sdk.ValAddress) error { return nil } diff --git a/x/gravity/keeper/invariants.go b/x/gravity/keeper/invariants.go index 1b3dbd14..43bf7b67 100644 --- a/x/gravity/keeper/invariants.go +++ b/x/gravity/keeper/invariants.go @@ -4,8 +4,10 @@ import ( "fmt" "sort" + "cosmossdk.io/math" "github.com/VolumeFi/whoops" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) @@ -40,11 +42,12 @@ func AllInvariants(k Keeper) sdk.Invariant { // Note that the returned bool should be true if there is an error, e.g. an unexpected module balance func ModuleBalanceInvariant(k Keeper) sdk.Invariant { return func(ctx sdk.Context) (string, bool) { + sdkCtx := sdk.UnwrapSDKContext(ctx) modAcc := k.accountKeeper.GetModuleAddress(types.ModuleName) actualBals := k.bankKeeper.GetAllBalances(ctx, modAcc) - expectedBals := make(map[string]*sdk.Int, len(actualBals)) // Collect balances by contract + expectedBals := make(map[string]*math.Int, len(actualBals)) // Collect balances by contract for _, v := range actualBals { - newInt := sdk.NewInt(0) + newInt := math.NewInt(0) expectedBals[v.Denom] = &newInt } expectedBals, err := sumUnconfirmedBatchModuleBalances(ctx, k, expectedBals) @@ -62,7 +65,7 @@ func ModuleBalanceInvariant(k Keeper) sdk.Invariant { _, err := k.GetERC20OfDenom(ctx, "test-chain", denom) if err != nil { // Here we do not return because a user could halt the chain by gifting gravity a cosmos asset with no erc20 repr - ctx.Logger().Error("Unexpected gravity module balance of paloma-originated asset with no erc20 representation", "asset", denom) + liblog.FromSDKLogger(k.Logger(sdkCtx)).WithFields("asset", denom).Error("Unexpected gravity module balance of paloma-originated asset with no erc20 representation") continue } expected, ok := expectedBals[denom] @@ -81,9 +84,9 @@ func ModuleBalanceInvariant(k Keeper) sdk.Invariant { /////// MODULE BALANCE HELPERS // sumUnconfirmedBatchModuleBalances calculate the value the module should have stored due to unconfirmed batches -func sumUnconfirmedBatchModuleBalances(ctx sdk.Context, k Keeper, expectedBals map[string]*sdk.Int) (map[string]*sdk.Int, error) { +func sumUnconfirmedBatchModuleBalances(ctx sdk.Context, k Keeper, expectedBals map[string]*math.Int) (map[string]*math.Int, error) { err := k.IterateOutgoingTxBatches(ctx, func(_ []byte, batch types.InternalOutgoingTxBatch) bool { - batchTotal := sdk.NewInt(0) + batchTotal := math.NewInt(0) // Collect the send amount for each tx for _, tx := range batch.Transactions { newTotal := batchTotal.Add(tx.Erc20Token.Amount) @@ -94,7 +97,7 @@ func sumUnconfirmedBatchModuleBalances(ctx sdk.Context, k Keeper, expectedBals m // Add the batch total to the contract counter _, ok := expectedBals[denom] if !ok { - zero := sdk.ZeroInt() + zero := math.ZeroInt() expectedBals[denom] = &zero } @@ -107,7 +110,7 @@ func sumUnconfirmedBatchModuleBalances(ctx sdk.Context, k Keeper, expectedBals m } // sumUnbatchedTxModuleBalances calculates the value the module should have stored due to unbatched txs -func sumUnbatchedTxModuleBalances(ctx sdk.Context, k Keeper, expectedBals map[string]*sdk.Int) (map[string]*sdk.Int, error) { +func sumUnbatchedTxModuleBalances(ctx sdk.Context, k Keeper, expectedBals map[string]*math.Int) (map[string]*math.Int, error) { // It is also given the balance of all unbatched txs in the pool err := k.IterateUnbatchedTransactions(ctx, func(_ []byte, tx *types.InternalOutgoingTransferTx) bool { contract := tx.Erc20Token.Contract @@ -115,7 +118,7 @@ func sumUnbatchedTxModuleBalances(ctx sdk.Context, k Keeper, expectedBals map[st _, ok := expectedBals[denom] if !ok { - zero := sdk.ZeroInt() + zero := math.ZeroInt() expectedBals[denom] = &zero } *expectedBals[denom] = expectedBals[denom].Add(tx.Erc20Token.Amount) diff --git a/x/gravity/keeper/invariants_test.go b/x/gravity/keeper/invariants_test.go index 0055e280..eca347b0 100644 --- a/x/gravity/keeper/invariants_test.go +++ b/x/gravity/keeper/invariants_test.go @@ -1,9 +1,11 @@ package keeper import ( + "context" "testing" "time" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" "github.com/palomachain/paloma/x/gravity/types" @@ -25,7 +27,7 @@ func TestModuleBalanceUnbatchedTxs(t *testing.T) { receiver, err := types.NewEthAddress(myReceiver) require.NoError(t, err) // mint some voucher first - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -41,7 +43,7 @@ func TestModuleBalanceUnbatchedTxs(t *testing.T) { // Create some unbatched transactions for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -62,7 +64,7 @@ func TestModuleBalanceUnbatchedTxs(t *testing.T) { checkInvariant(t, ctx, input.GravityKeeper, true) // Ensure an error is returned for a mismatched balance - oneVoucher, err := types.NewInternalERC20Token(sdk.NewInt(1), testERC20Address, "test-chain") + oneVoucher, err := types.NewInternalERC20Token(math.NewInt(1), testERC20Address, "test-chain") require.NoError(t, err) checkImbalancedModule(t, ctx, input.GravityKeeper, input.BankKeeper, mySender, sdk.NewCoins(sdk.NewCoin(testDenom, oneVoucher.Amount))) @@ -72,7 +74,8 @@ func TestModuleBalanceUnbatchedTxs(t *testing.T) { func TestModuleBalanceBatchedTxs(t *testing.T) { ////////////////// SETUP ////////////////// input, ctx := SetupFiveValChain(t) - defer func() { ctx.Logger().Info("Asserting invariants at test end"); input.AssertInvariants() }() + sdkCtx := sdk.UnwrapSDKContext(ctx) + defer func() { sdkCtx.Logger().Info("Asserting invariants at test end"); input.AssertInvariants() }() var ( now = time.Now().UTC() @@ -83,9 +86,9 @@ func TestModuleBalanceBatchedTxs(t *testing.T) { require.NoError(t, e1) require.NoError(t, e2) require.NoError(t, e3) - token, err := types.NewInternalERC20Token(sdk.NewInt(150000000000000), myTokenContractAddr.GetAddress().Hex(), "test-chain") + token, err := types.NewInternalERC20Token(math.NewInt(150000000000000), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) - voucher, err := types.NewInternalERC20Token(sdk.NewInt(1), myTokenContractAddr.GetAddress().Hex(), "test-chain") + voucher, err := types.NewInternalERC20Token(math.NewInt(1), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) voucherCoin := sdk.NewCoins(sdk.NewCoin(testDenom, voucher.Amount)) tokenCoin := sdk.NewCoins(sdk.NewCoin(testDenom, token.Amount)) @@ -105,7 +108,7 @@ func TestModuleBalanceBatchedTxs(t *testing.T) { // add some TX to the pool for i := 0; i < 8; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), token.Contract.GetAddress().Hex(), "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), token.Contract.GetAddress().Hex(), "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -122,7 +125,7 @@ func TestModuleBalanceBatchedTxs(t *testing.T) { // Create a batch, perform some checks // when - ctx = ctx.WithBlockTime(now) + ctx = sdkCtx.WithBlockTime(now) // tx batch size is 3, so that some of them stay behind batch, err := input.GravityKeeper.BuildOutgoingTXBatch(ctx, "test-chain", token.Contract, 3) require.NoError(t, err) @@ -155,8 +158,9 @@ func TestModuleBalanceBatchedTxs(t *testing.T) { checkImbalancedModule(t, ctx, input.GravityKeeper, input.BankKeeper, mySender, voucherCoin) } -func checkInvariant(t *testing.T, ctx sdk.Context, k Keeper, succeed bool) { - res, ok := ModuleBalanceInvariant(k)(ctx) +func checkInvariant(t *testing.T, ctx context.Context, k Keeper, succeed bool) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + res, ok := ModuleBalanceInvariant(k)(sdkCtx) if succeed { require.False(t, ok, "Invariant should have returned false") require.Empty(t, res, "Invariant should have returned no message") @@ -166,7 +170,7 @@ func checkInvariant(t *testing.T, ctx sdk.Context, k Keeper, succeed bool) { } } -func checkImbalancedModule(t *testing.T, ctx sdk.Context, gravityKeeper Keeper, bankKeeper bankkeeper.BaseKeeper, sender sdk.AccAddress, coins sdk.Coins) { +func checkImbalancedModule(t *testing.T, ctx context.Context, gravityKeeper Keeper, bankKeeper bankkeeper.BaseKeeper, sender sdk.AccAddress, coins sdk.Coins) { // Imbalance the module require.NoError(t, bankKeeper.SendCoinsFromAccountToModule(ctx, sender, types.ModuleName, coins)) checkInvariant(t, ctx, gravityKeeper, false) diff --git a/x/gravity/keeper/keeper.go b/x/gravity/keeper/keeper.go index f4fc47a3..baf4ee1e 100644 --- a/x/gravity/keeper/keeper.go +++ b/x/gravity/keeper/keeper.go @@ -1,12 +1,14 @@ package keeper import ( + "context" "fmt" + "cosmossdk.io/core/address" sdkerrors "cosmossdk.io/errors" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + storetypes "cosmossdk.io/store/types" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrortypes "github.com/cosmos/cosmos-sdk/types/errors" distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" @@ -15,8 +17,9 @@ import ( slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" + ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" keeperutil "github.com/palomachain/paloma/util/keeper" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) @@ -35,15 +38,15 @@ type Keeper struct { bankKeeper types.BankKeeper StakingKeeper types.StakingKeeper SlashingKeeper types.SlashingKeeper - DistKeeper types.DistributionKeeper + DistKeeper distrkeeper.Keeper accountKeeper types.AccountKeeper ibcTransferKeeper ibctransferkeeper.Keeper evmKeeper types.EVMKeeper - - storeGetter keeperutil.StoreGetter + addressCodec address.Codec + storeGetter keeperutil.StoreGetter AttestationHandler interface { - Handle(sdk.Context, types.Attestation, types.EthereumClaim) error + Handle(context.Context, types.Attestation, types.EthereumClaim) error } } @@ -55,7 +58,7 @@ func NewKeeper( stakingKeeper types.StakingKeeper, bankKeeper types.BankKeeper, slashingKeeper types.SlashingKeeper, - distributionKeeper types.DistributionKeeper, + distributionKeeper distrkeeper.Keeper, ibcTransferKeeper ibctransferkeeper.Keeper, evmKeeper types.EVMKeeper, storeGetter keeperutil.StoreGetter, @@ -93,14 +96,16 @@ func NewKeeper( // SendToCommunityPool handles incorrect SendToPaloma calls to the community pool, since the calls // have already been made on Ethereum there's nothing we can do to reverse them, and we should at least // make use of the tokens which would otherwise be lost -func (k Keeper) SendToCommunityPool(ctx sdk.Context, coins sdk.Coins) error { +func (k Keeper) SendToCommunityPool(ctx context.Context, coins sdk.Coins) error { if err := k.bankKeeper.SendCoinsFromModuleToModule(ctx, types.ModuleName, distrtypes.ModuleName, coins); err != nil { return sdkerrors.Wrap(err, "transfer to community pool failed") } - feePool := k.DistKeeper.GetFeePool(ctx) + feePool, err := k.DistKeeper.FeePool.Get(ctx) + if err != nil { + return err + } feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(coins...)...) - k.DistKeeper.SetFeePool(ctx, feePool) - return nil + return k.DistKeeper.FeePool.Set(ctx, feePool) } ///////////////////////////// @@ -110,32 +115,36 @@ func (k Keeper) SendToCommunityPool(ctx sdk.Context, coins sdk.Coins) error { // GetParamsIfSet returns the parameters from the store if they exist, or an error // This is useful for certain contexts where the store is not yet set up, like // in an AnteHandler during InitGenesis -func (k Keeper) GetParamsIfSet(ctx sdk.Context) (params types.Params, err error) { +func (k Keeper) GetParamsIfSet(ctx context.Context) (params types.Params, err error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) for _, pair := range params.ParamSetPairs() { - if !k.paramSpace.Has(ctx, pair.Key) { + if !k.paramSpace.Has(sdkCtx, pair.Key) { return types.Params{}, sdkerrors.Wrapf(sdkerrortypes.ErrNotFound, "the param key %s has not been set", string(pair.Key)) } - k.paramSpace.Get(ctx, pair.Key, pair.Value) + k.paramSpace.Get(sdkCtx, pair.Key, pair.Value) } return } // GetParams returns the parameters from the store -func (k Keeper) GetParams(ctx sdk.Context) (params types.Params) { - k.paramSpace.GetParamSet(ctx, ¶ms) +func (k Keeper) GetParams(ctx context.Context) (params types.Params) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.paramSpace.GetParamSet(sdkCtx, ¶ms) return } // SetParams sets the parameters in the store -func (k Keeper) SetParams(ctx sdk.Context, ps types.Params) { - k.paramSpace.SetParamSet(ctx, &ps) +func (k Keeper) SetParams(ctx context.Context, ps types.Params) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.paramSpace.SetParamSet(sdkCtx, &ps) } // GetBridgeContractAddress returns the bridge contract address on ETH -func (k Keeper) GetBridgeContractAddress(ctx sdk.Context) (*types.EthAddress, error) { +func (k Keeper) GetBridgeContractAddress(ctx context.Context) (*types.EthAddress, error) { var a string - k.paramSpace.Get(ctx, types.ParamsStoreKeyBridgeEthereumAddress, &a) + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.paramSpace.Get(sdkCtx, types.ParamsStoreKeyBridgeEthereumAddress, &a) addr, err := types.NewEthAddress(a) if err != nil { return nil, sdkerrors.Wrapf(err, "found invalid bridge contract address in store: %v", a) @@ -144,15 +153,16 @@ func (k Keeper) GetBridgeContractAddress(ctx sdk.Context) (*types.EthAddress, er } // GetBridgeChainID returns the chain id of the ETH chain we are running against -func (k Keeper) GetBridgeChainID(ctx sdk.Context) uint64 { +func (k Keeper) GetBridgeChainID(ctx context.Context) uint64 { var a uint64 - k.paramSpace.Get(ctx, types.ParamsStoreKeyBridgeContractChainID, &a) + sdkCtx := sdk.UnwrapSDKContext(ctx) + k.paramSpace.Get(sdkCtx, types.ParamsStoreKeyBridgeContractChainID, &a) return a } // Logger returns a module-specific Logger. -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +func (k Keeper) Logger(ctx context.Context) log.Logger { + return liblog.FromSDKLogger(k.Logger(ctx)).With("module", fmt.Sprintf("x/%s", types.ModuleName)) } func (k Keeper) UnpackAttestationClaim(att *types.Attestation) (types.EthereumClaim, error) { @@ -220,12 +230,13 @@ func (k Keeper) DeserializeValidatorIterator(vals []byte) stakingtypes.ValAddres // it is invalid for a subset of ERC20 addresses. (2) is not yet implemented // Blocking some addresses is technically motivated, if any ERC20 transfers in a batch fail the entire batch // becomes impossible to execute. -func (k Keeper) InvalidSendToEthAddress(ctx sdk.Context, addr types.EthAddress, _erc20Addr types.EthAddress) bool { +func (k Keeper) InvalidSendToEthAddress(ctx context.Context, addr types.EthAddress, _erc20Addr types.EthAddress) bool { return addr == types.ZeroAddress() } -func (k Keeper) GetStore(ctx sdk.Context) sdk.KVStore { - return k.storeGetter.Store(ctx) +func (k Keeper) GetStore(ctx context.Context) storetypes.KVStore { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return k.storeGetter.Store(sdkCtx) } type GravityStoreGetter struct { @@ -238,6 +249,7 @@ func NewGravityStoreGetter(storeKey storetypes.StoreKey) GravityStoreGetter { } } -func (gsg GravityStoreGetter) Store(ctx sdk.Context) sdk.KVStore { - return ctx.KVStore(gsg.storeKey) +func (gsg GravityStoreGetter) Store(ctx context.Context) storetypes.KVStore { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.KVStore(gsg.storeKey) } diff --git a/x/gravity/keeper/keeper_batch.go b/x/gravity/keeper/keeper_batch.go index f065f9d7..2244b148 100644 --- a/x/gravity/keeper/keeper_batch.go +++ b/x/gravity/keeper/keeper_batch.go @@ -1,9 +1,12 @@ package keeper import ( + "context" + sdkerrors "cosmossdk.io/errors" - "github.com/cosmos/cosmos-sdk/store/prefix" + "cosmossdk.io/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) @@ -12,10 +15,10 @@ import ( ///////////////////////////// // GetBatchConfirm returns a batch confirmation given its nonce, the token contract, and a validator address -func (k Keeper) GetBatchConfirm(ctx sdk.Context, nonce uint64, tokenContract types.EthAddress, validator sdk.AccAddress) (*types.MsgConfirmBatch, error) { +func (k Keeper) GetBatchConfirm(ctx context.Context, nonce uint64, tokenContract types.EthAddress, validator sdk.AccAddress) (*types.MsgConfirmBatch, error) { store := k.GetStore(ctx) if err := sdk.VerifyAddressFormat(validator); err != nil { - ctx.Logger().Error("invalid validator address") + liblog.FromSDKLogger(k.Logger(ctx)).WithError(err).Error("invalid validator address") return nil, nil } batchConfirmKey, err := types.GetBatchConfirmKey(tokenContract, nonce, validator) @@ -38,7 +41,7 @@ func (k Keeper) GetBatchConfirm(ctx sdk.Context, nonce uint64, tokenContract typ } // SetBatchConfirm sets a batch confirmation by a validator -func (k Keeper) SetBatchConfirm(ctx sdk.Context, batch *types.MsgConfirmBatch) ([]byte, error) { +func (k Keeper) SetBatchConfirm(ctx context.Context, batch *types.MsgConfirmBatch) ([]byte, error) { store := k.GetStore(ctx) acc, err := sdk.AccAddressFromBech32(batch.Orchestrator) if err != nil { @@ -57,7 +60,7 @@ func (k Keeper) SetBatchConfirm(ctx sdk.Context, batch *types.MsgConfirmBatch) ( } // DeleteBatchConfirms deletes confirmations for an outgoing transaction batch -func (k Keeper) DeleteBatchConfirms(ctx sdk.Context, batch types.InternalOutgoingTxBatch) error { +func (k Keeper) DeleteBatchConfirms(ctx context.Context, batch types.InternalOutgoingTxBatch) error { store := k.GetStore(ctx) batchConfirms, err := k.GetBatchConfirmByNonceAndTokenContract(ctx, batch.BatchNonce, batch.TokenContract) if err != nil { @@ -82,7 +85,7 @@ func (k Keeper) DeleteBatchConfirms(ctx sdk.Context, batch types.InternalOutgoin // IterateBatchConfirmByNonceAndTokenContract iterates through all batch confirmations // MARK finish-batches: this is where the key is iterated in the old (presumed working) code // TODO: specify which nonce this is -func (k Keeper) IterateBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonce uint64, tokenContract types.EthAddress, cb func([]byte, types.MsgConfirmBatch) bool) error { +func (k Keeper) IterateBatchConfirmByNonceAndTokenContract(ctx context.Context, nonce uint64, tokenContract types.EthAddress, cb func([]byte, types.MsgConfirmBatch) bool) error { store := k.GetStore(ctx) prefix := types.GetBatchConfirmNonceContractPrefix(tokenContract, nonce) start, end, err := prefixRange(prefix) @@ -111,7 +114,7 @@ func (k Keeper) IterateBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonc } // GetBatchConfirmByNonceAndTokenContract returns the batch confirms -func (k Keeper) GetBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonce uint64, tokenContract types.EthAddress) (out []types.MsgConfirmBatch, err error) { +func (k Keeper) GetBatchConfirmByNonceAndTokenContract(ctx context.Context, nonce uint64, tokenContract types.EthAddress) (out []types.MsgConfirmBatch, err error) { err = k.IterateBatchConfirmByNonceAndTokenContract(ctx, nonce, tokenContract, func(_ []byte, msg types.MsgConfirmBatch) bool { out = append(out, msg) return false @@ -120,7 +123,7 @@ func (k Keeper) GetBatchConfirmByNonceAndTokenContract(ctx sdk.Context, nonce ui } // IterateBatchConfirms iterates through all batch confirmations -func (k Keeper) IterateBatchConfirms(ctx sdk.Context, cb func([]byte, types.MsgConfirmBatch) (stop bool)) { +func (k Keeper) IterateBatchConfirms(ctx context.Context, cb func([]byte, types.MsgConfirmBatch) (stop bool)) { store := k.GetStore(ctx) prefixStore := prefix.NewStore(store, types.BatchConfirmKey) iter := prefixStore.Iterator(nil, nil) diff --git a/x/gravity/keeper/keeper_delegate_key.go b/x/gravity/keeper/keeper_delegate_key.go index ea9238b7..640544a2 100644 --- a/x/gravity/keeper/keeper_delegate_key.go +++ b/x/gravity/keeper/keeper_delegate_key.go @@ -1,10 +1,12 @@ package keeper import ( + "context" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/gravity/types" ) @@ -13,18 +15,22 @@ import ( /////////////////////////// // GetOrchestratorValidator returns the validator key associated with an orchestrator key -func (k Keeper) GetOrchestratorValidator(ctx sdk.Context, orch sdk.AccAddress) (validator stakingtypes.Validator, found bool, err error) { +func (k Keeper) GetOrchestratorValidator(ctx context.Context, orch sdk.AccAddress) (validator stakingtypes.Validator, found bool, err error) { valAddr := sdk.ValAddress(orch) if valAddr == nil { return validator, false, fmt.Errorf("nil valAddr") } if err := sdk.VerifyAddressFormat(orch); err != nil { - ctx.Logger().Error("invalid orch address") + liblog.FromSDKLogger(k.Logger(ctx)).WithError(err).Error("invalid orch address") return validator, false, err } - validator, found = k.StakingKeeper.GetValidator(ctx, valAddr) + validator, err = k.StakingKeeper.GetValidator(ctx, valAddr) + if err != nil { + liblog.FromSDKLogger(k.Logger(ctx)).WithError(err).Error("unable to get validator") + return validator, false, err + } return validator, true, nil } @@ -34,12 +40,12 @@ func (k Keeper) GetOrchestratorValidator(ctx sdk.Context, orch sdk.AccAddress) ( ///////////////////////////// // GetEthAddressByValidator returns the eth address for a given gravity validator -func (k Keeper) GetEthAddressByValidator(ctx sdk.Context, validator sdk.ValAddress, chainReferenceId string) (ethAddress *types.EthAddress, found bool, err error) { +func (k Keeper) GetEthAddressByValidator(ctx context.Context, validator sdk.ValAddress, chainReferenceId string) (ethAddress *types.EthAddress, found bool, err error) { return k.evmKeeper.GetEthAddressByValidator(ctx, validator, chainReferenceId) } // GetValidatorByEthAddress returns the validator for a given eth address -func (k Keeper) GetValidatorByEthAddress(ctx sdk.Context, ethAddr types.EthAddress, chainReferenceId string) (validator stakingtypes.Validator, found bool, err error) { +func (k Keeper) GetValidatorByEthAddress(ctx context.Context, ethAddr types.EthAddress, chainReferenceId string) (validator stakingtypes.Validator, found bool, err error) { valAddr, found, err := k.evmKeeper.GetValidatorAddressByEthAddress(ctx, ethAddr, chainReferenceId) if err != nil { return validator, false, err @@ -47,6 +53,6 @@ func (k Keeper) GetValidatorByEthAddress(ctx sdk.Context, ethAddr types.EthAddre if valAddr == nil { return validator, false, nil } - validator, found = k.StakingKeeper.GetValidator(ctx, valAddr) + validator, err = k.StakingKeeper.GetValidator(ctx, valAddr) return validator, found, nil } diff --git a/x/gravity/keeper/keeper_test.go b/x/gravity/keeper/keeper_test.go index c460a0df..07915ef0 100644 --- a/x/gravity/keeper/keeper_test.go +++ b/x/gravity/keeper/keeper_test.go @@ -3,8 +3,8 @@ package keeper import ( "testing" + "cosmossdk.io/math" codecTypes "github.com/cosmos/cosmos-sdk/codec/types" - sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" vtypes "github.com/palomachain/paloma/x/valset/types" "github.com/stretchr/testify/assert" @@ -57,7 +57,7 @@ func TestAttestationIterator(t *testing.T) { claim1 := &types.MsgSendToPalomaClaim{ EventNonce: 1, TokenContract: TokenContractAddrs[0], - Amount: sdk.NewInt(100), + Amount: math.NewInt(100), EthereumSender: EthAddrs[0].String(), PalomaReceiver: AccAddrs[0].String(), Orchestrator: AccAddrs[0].String(), @@ -77,7 +77,7 @@ func TestAttestationIterator(t *testing.T) { claim2 := &types.MsgSendToPalomaClaim{ EventNonce: 2, TokenContract: TokenContractAddrs[0], - Amount: sdk.NewInt(100), + Amount: math.NewInt(100), EthereumSender: EthAddrs[0].String(), PalomaReceiver: AccAddrs[0].String(), Orchestrator: AccAddrs[0].String(), diff --git a/x/gravity/keeper/msg_server.go b/x/gravity/keeper/msg_server.go index 9ecb9453..6b617ab7 100644 --- a/x/gravity/keeper/msg_server.go +++ b/x/gravity/keeper/msg_server.go @@ -5,9 +5,11 @@ import ( "encoding/hex" "fmt" + sdkerrors "cosmossdk.io/errors" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "github.com/cosmos/cosmos-sdk/types/errors" + keeperutil "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/x/gravity/types" ) @@ -119,7 +121,7 @@ func (k msgServer) ConfirmBatch(c context.Context, msg *types.MsgConfirmBatch) ( // checkOrchestratorValidatorInSet checks that the orchestrator refers to a validator that is // currently in the set -func (k msgServer) checkOrchestratorValidatorInSet(ctx sdk.Context, orchestrator string) error { +func (k msgServer) checkOrchestratorValidatorInSet(ctx context.Context, orchestrator string) error { orchaddr, err := sdk.AccAddressFromBech32(orchestrator) if err != nil { return sdkerrors.Wrap(types.ErrInvalid, "acc address invalid") @@ -131,11 +133,17 @@ func (k msgServer) checkOrchestratorValidatorInSet(ctx sdk.Context, orchestrator if !found { return sdkerrors.Wrap(types.ErrUnknown, "validator") } - + valAddress, err := keeperutil.ValAddressFromBech32(k.addressCodec, validator.GetOperator()) + if err != nil { + return err + } // return an error if the validator isn't in the active set - val := k.StakingKeeper.Validator(ctx, validator.GetOperator()) + val, err := k.StakingKeeper.Validator(ctx, valAddress) + if err != nil { + return err + } if val == nil || !val.IsBonded() { - return sdkerrors.Wrap(sdkerrors.ErrorInvalidSigner, "validator not in active set") + return sdkerrors.Wrap(errorsmod.ErrorInvalidSigner, "validator not in active set") } return nil @@ -143,7 +151,7 @@ func (k msgServer) checkOrchestratorValidatorInSet(ctx sdk.Context, orchestrator // claimHandlerCommon is an internal function that provides common code for processing claims once they are // translated from the message to the Ethereum claim interface -func (k msgServer) claimHandlerCommon(ctx sdk.Context, msgAny *codectypes.Any, msg types.EthereumClaim) error { +func (k msgServer) claimHandlerCommon(ctx context.Context, msgAny *codectypes.Any, msg types.EthereumClaim) error { // Add the claim to the store _, err := k.Attest(ctx, msg, msgAny) if err != nil { @@ -153,9 +161,9 @@ func (k msgServer) claimHandlerCommon(ctx sdk.Context, msgAny *codectypes.Any, m if err != nil { return sdkerrors.Wrap(err, "unable to compute claim hash") } - + sdkCtx := sdk.UnwrapSDKContext(ctx) // Emit the handle message event - return ctx.EventManager().EmitTypedEvent( + return sdkCtx.EventManager().EmitTypedEvent( &types.EventClaim{ Message: msg.GetType().String(), ClaimHash: fmt.Sprintf("%x", hash), @@ -165,7 +173,7 @@ func (k msgServer) claimHandlerCommon(ctx sdk.Context, msgAny *codectypes.Any, m } // confirmHandlerCommon is an internal function that provides common code for processing claim messages -func (k msgServer) confirmHandlerCommon(ctx sdk.Context, ethAddress string, orchestrator sdk.AccAddress, signature string, checkpoint []byte, chainReferenceId string) error { +func (k msgServer) confirmHandlerCommon(ctx context.Context, ethAddress string, orchestrator sdk.AccAddress, signature string, checkpoint []byte, chainReferenceId string) error { sigBytes, err := hex.DecodeString(signature) if err != nil { return sdkerrors.Wrap(types.ErrInvalid, "signature decoding") @@ -183,17 +191,17 @@ func (k msgServer) confirmHandlerCommon(ctx sdk.Context, ethAddress string, orch if !found { return sdkerrors.Wrap(types.ErrUnknown, "validator") } - + valAddress, err := keeperutil.ValAddressFromBech32(k.addressCodec, validator.GetOperator()) if !validator.IsBonded() && !validator.IsUnbonding() { // We must only accept confirms from bonded or unbonding validators return sdkerrors.Wrap(types.ErrInvalid, "validator is unbonded") } - if err := sdk.VerifyAddressFormat(validator.GetOperator()); err != nil { + if err := sdk.VerifyAddressFormat(valAddress); err != nil { return sdkerrors.Wrapf(err, "discovered invalid validator address for orchestrator %v", orchestrator) } - ethAddressFromStore, found, err := k.GetEthAddressByValidator(ctx, validator.GetOperator(), chainReferenceId) + ethAddressFromStore, found, err := k.GetEthAddressByValidator(ctx, valAddress, chainReferenceId) if err != nil { return err } @@ -262,7 +270,7 @@ func (k msgServer) BatchSendToEthClaim(c context.Context, msg *types.MsgBatchSen } // Performs additional checks on msg to determine if it is valid -func additionalPatchChecks(ctx sdk.Context, k msgServer, msg *types.MsgBatchSendToEthClaim) error { +func additionalPatchChecks(ctx context.Context, k msgServer, msg *types.MsgBatchSendToEthClaim) error { contractAddress, err := types.NewEthAddress(msg.TokenContract) if err != nil { return sdkerrors.Wrap(err, "Invalid TokenContract on MsgBatchSendToEthClaim") diff --git a/x/gravity/keeper/pool.go b/x/gravity/keeper/pool.go index a3ae04f5..30f353d4 100644 --- a/x/gravity/keeper/pool.go +++ b/x/gravity/keeper/pool.go @@ -1,11 +1,12 @@ package keeper import ( + "context" "fmt" "strconv" + sdkerrors "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/palomachain/paloma/x/gravity/types" ) @@ -17,13 +18,14 @@ import ( // - persists an OutgoingTx // - adds the TX to the `available` TX pool func (k Keeper) AddToOutgoingPool( - ctx sdk.Context, + ctx context.Context, sender sdk.AccAddress, counterpartReceiver types.EthAddress, amount sdk.Coin, chainReferenceID string, ) (uint64, error) { - if ctx.IsZero() || sdk.VerifyAddressFormat(sender) != nil || counterpartReceiver.ValidateBasic() != nil || + sdkCtx := sdk.UnwrapSDKContext(ctx) + if sdkCtx.IsZero() || sdk.VerifyAddressFormat(sender) != nil || counterpartReceiver.ValidateBasic() != nil || !amount.IsValid() { return 0, sdkerrors.Wrap(types.ErrInvalid, "arguments") } @@ -74,7 +76,7 @@ func (k Keeper) AddToOutgoingPool( if err != nil { return 0, err } - return nextID, ctx.EventManager().EmitTypedEvent( + return nextID, sdkCtx.EventManager().EmitTypedEvent( &types.EventWithdrawalReceived{ BridgeContract: bridgeContractAddress.GetAddress().Hex(), BridgeChainId: strconv.Itoa(int(k.GetBridgeChainID(ctx))), @@ -88,8 +90,9 @@ func (k Keeper) AddToOutgoingPool( // - checks that the provided tx actually exists // - deletes the unbatched tx from the pool // - issues the tokens back to the sender -func (k Keeper) RemoveFromOutgoingPoolAndRefund(ctx sdk.Context, txId uint64, sender sdk.AccAddress) error { - if ctx.IsZero() || txId < 1 || sdk.VerifyAddressFormat(sender) != nil { +func (k Keeper) RemoveFromOutgoingPoolAndRefund(ctx context.Context, txId uint64, sender sdk.AccAddress) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + if sdkCtx.IsZero() || txId < 1 || sdk.VerifyAddressFormat(sender) != nil { return sdkerrors.Wrap(types.ErrInvalid, "arguments") } // check that we actually have a tx with that id and what it's details are @@ -133,7 +136,7 @@ func (k Keeper) RemoveFromOutgoingPoolAndRefund(ctx sdk.Context, txId uint64, se return err } - return ctx.EventManager().EmitTypedEvent( + return sdkCtx.EventManager().EmitTypedEvent( &types.EventWithdrawCanceled{ Sender: sender.String(), TxId: fmt.Sprint(txId), @@ -145,7 +148,7 @@ func (k Keeper) RemoveFromOutgoingPoolAndRefund(ctx sdk.Context, txId uint64, se // addUnbatchedTx creates a new transaction in the pool // WARNING: Do not make this function public -func (k Keeper) addUnbatchedTX(ctx sdk.Context, val *types.InternalOutgoingTransferTx) error { +func (k Keeper) addUnbatchedTX(ctx context.Context, val *types.InternalOutgoingTransferTx) error { store := k.GetStore(ctx) idxKey := types.GetOutgoingTxPoolKey(*val.Erc20Token, val.Id) if store.Has(idxKey) { @@ -165,7 +168,7 @@ func (k Keeper) addUnbatchedTX(ctx sdk.Context, val *types.InternalOutgoingTrans // removeUnbatchedTXIndex removes the tx from the pool // WARNING: Do not make this function public -func (k Keeper) removeUnbatchedTX(ctx sdk.Context, token types.InternalERC20Token, txID uint64) error { +func (k Keeper) removeUnbatchedTX(ctx context.Context, token types.InternalERC20Token, txID uint64) error { store := k.GetStore(ctx) idxKey := types.GetOutgoingTxPoolKey(token, txID) if !store.Has(idxKey) { @@ -180,7 +183,7 @@ func (k Keeper) removeUnbatchedTX(ctx sdk.Context, token types.InternalERC20Toke /////////////////////////////////////////////////////////////////////////////////////// // GetUnbatchedTxByAmountAndId grabs a tx from the pool given its txID -func (k Keeper) GetUnbatchedTxByAmountAndId(ctx sdk.Context, token types.InternalERC20Token, txID uint64) (*types.InternalOutgoingTransferTx, error) { +func (k Keeper) GetUnbatchedTxByAmountAndId(ctx context.Context, token types.InternalERC20Token, txID uint64) (*types.InternalOutgoingTransferTx, error) { store := k.GetStore(ctx) bz := store.Get(types.GetOutgoingTxPoolKey(token, txID)) if bz == nil { @@ -200,7 +203,7 @@ func (k Keeper) GetUnbatchedTxByAmountAndId(ctx sdk.Context, token types.Interna // GetUnbatchedTxById grabs a tx from the pool given only the txID // note that due to the way unbatched txs are indexed, the GetUnbatchedTxByAmountAndId method is much faster -func (k Keeper) GetUnbatchedTxById(ctx sdk.Context, txID uint64) (*types.InternalOutgoingTransferTx, error) { +func (k Keeper) GetUnbatchedTxById(ctx context.Context, txID uint64) (*types.InternalOutgoingTransferTx, error) { var r *types.InternalOutgoingTransferTx = nil err := k.IterateUnbatchedTransactions(ctx, func(_ []byte, tx *types.InternalOutgoingTransferTx) bool { if tx.Id == txID { @@ -222,17 +225,17 @@ func (k Keeper) GetUnbatchedTxById(ctx sdk.Context, txID uint64) (*types.Interna // GetUnbatchedTransactionsByContract grabs all unbatched transactions from the tx pool for the given contract // unbatched transactions are sorted by nonce in DESC order -func (k Keeper) GetUnbatchedTransactionsByContract(ctx sdk.Context, contractAddress types.EthAddress) ([]*types.InternalOutgoingTransferTx, error) { +func (k Keeper) GetUnbatchedTransactionsByContract(ctx context.Context, contractAddress types.EthAddress) ([]*types.InternalOutgoingTransferTx, error) { return k.collectUnbatchedTransactions(ctx, types.GetOutgoingTxPoolContractPrefix(contractAddress)) } // GetUnbatchedTransactions grabs all transactions from the tx pool, useful for queries or genesis save/load -func (k Keeper) GetUnbatchedTransactions(ctx sdk.Context) ([]*types.InternalOutgoingTransferTx, error) { +func (k Keeper) GetUnbatchedTransactions(ctx context.Context) ([]*types.InternalOutgoingTransferTx, error) { return k.collectUnbatchedTransactions(ctx, types.OutgoingTXPoolKey) } // Aggregates all unbatched transactions in the store with a given prefix -func (k Keeper) collectUnbatchedTransactions(ctx sdk.Context, prefixKey []byte) (out []*types.InternalOutgoingTransferTx, err error) { +func (k Keeper) collectUnbatchedTransactions(ctx context.Context, prefixKey []byte) (out []*types.InternalOutgoingTransferTx, err error) { err = k.filterAndIterateUnbatchedTransactions(ctx, prefixKey, func(_ []byte, tx *types.InternalOutgoingTransferTx) bool { out = append(out, tx) return false @@ -243,20 +246,20 @@ func (k Keeper) collectUnbatchedTransactions(ctx sdk.Context, prefixKey []byte) // IterateUnbatchedTransactionsByContract iterates through unbatched transactions from the tx pool for the given contract, // executing the given callback on each discovered Tx. Return true in cb to stop iteration, false to continue. // unbatched transactions are sorted by nonce in DESC order -func (k Keeper) IterateUnbatchedTransactionsByContract(ctx sdk.Context, contractAddress types.EthAddress, cb func(key []byte, tx *types.InternalOutgoingTransferTx) bool) error { +func (k Keeper) IterateUnbatchedTransactionsByContract(ctx context.Context, contractAddress types.EthAddress, cb func(key []byte, tx *types.InternalOutgoingTransferTx) bool) error { return k.filterAndIterateUnbatchedTransactions(ctx, types.GetOutgoingTxPoolContractPrefix(contractAddress), cb) } // IterateUnbatchedTransactions iterates through all unbatched transactions in DESC order, executing the given callback // on each discovered Tx. Return true in cb to stop iteration, false to continue. // For finer grained control, use filterAndIterateUnbatchedTransactions or one of the above methods -func (k Keeper) IterateUnbatchedTransactions(ctx sdk.Context, cb func(key []byte, tx *types.InternalOutgoingTransferTx) (stop bool)) error { +func (k Keeper) IterateUnbatchedTransactions(ctx context.Context, cb func(key []byte, tx *types.InternalOutgoingTransferTx) (stop bool)) error { return k.filterAndIterateUnbatchedTransactions(ctx, types.OutgoingTXPoolKey, cb) } // filterAndIterateUnbatchedTransactions iterates through all unbatched transactions whose keys begin with prefixKey in DESC order // prefixKey should be either OutgoingTXPoolKey or some more granular key, passing the wrong key will cause an error -func (k Keeper) filterAndIterateUnbatchedTransactions(ctx sdk.Context, prefixKey []byte, cb func(key []byte, tx *types.InternalOutgoingTransferTx) bool) error { +func (k Keeper) filterAndIterateUnbatchedTransactions(ctx context.Context, prefixKey []byte, cb func(key []byte, tx *types.InternalOutgoingTransferTx) bool) error { prefixStore := k.GetStore(ctx) start, end, err := prefixRange(prefixKey) if err != nil { @@ -283,7 +286,7 @@ func (k Keeper) filterAndIterateUnbatchedTransactions(ctx sdk.Context, prefixKey // returning, initializing and incrementing all at once. This is particularly // used for the transaction pool and batch pool where each batch or transaction is // assigned a unique ID. -func (k Keeper) autoIncrementID(ctx sdk.Context, idKey []byte) (uint64, error) { +func (k Keeper) autoIncrementID(ctx context.Context, idKey []byte) (uint64, error) { id, err := k.getID(ctx, idKey) if err != nil { return 0, err @@ -294,7 +297,7 @@ func (k Keeper) autoIncrementID(ctx sdk.Context, idKey []byte) (uint64, error) { } // gets a generic uint64 counter from the store, initializing to 1 if no value exists -func (k Keeper) getID(ctx sdk.Context, idKey []byte) (uint64, error) { +func (k Keeper) getID(ctx context.Context, idKey []byte) (uint64, error) { store := k.GetStore(ctx) bz := store.Get(idKey) id, err := types.UInt64FromBytes(bz) @@ -305,7 +308,7 @@ func (k Keeper) getID(ctx sdk.Context, idKey []byte) (uint64, error) { } // sets a generic uint64 counter in the store -func (k Keeper) setID(ctx sdk.Context, id uint64, idKey []byte) { +func (k Keeper) setID(ctx context.Context, id uint64, idKey []byte) { store := k.GetStore(ctx) bz := sdk.Uint64ToBigEndian(id) store.Set(idKey, bz) diff --git a/x/gravity/keeper/pool_test.go b/x/gravity/keeper/pool_test.go index 27a93c84..66a43ec9 100644 --- a/x/gravity/keeper/pool_test.go +++ b/x/gravity/keeper/pool_test.go @@ -1,9 +1,11 @@ package keeper import ( + "context" "fmt" "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/gravity/types" "github.com/stretchr/testify/assert" @@ -26,7 +28,7 @@ func TestAddToOutgoingPool(t *testing.T) { tokenContract, err := types.NewEthAddress(testERC20Address) require.NoError(t, err) // mint some voucher first - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -39,7 +41,7 @@ func TestAddToOutgoingPool(t *testing.T) { // when for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -59,13 +61,13 @@ func TestAddToOutgoingPool(t *testing.T) { receiverAddr, err := types.NewEthAddress(myReceiver) require.NoError(t, err) - oneHundredTok, err := types.NewInternalERC20Token(sdk.NewInt(100), testERC20Address, "test-chain") + oneHundredTok, err := types.NewInternalERC20Token(math.NewInt(100), testERC20Address, "test-chain") require.NoError(t, err) - oneHundredOneTok, err := types.NewInternalERC20Token(sdk.NewInt(101), testERC20Address, "test-chain") + oneHundredOneTok, err := types.NewInternalERC20Token(math.NewInt(101), testERC20Address, "test-chain") require.NoError(t, err) - oneHundredTwoTok, err := types.NewInternalERC20Token(sdk.NewInt(102), testERC20Address, "test-chain") + oneHundredTwoTok, err := types.NewInternalERC20Token(math.NewInt(102), testERC20Address, "test-chain") require.NoError(t, err) - oneHundredThreeTok, err := types.NewInternalERC20Token(sdk.NewInt(103), testERC20Address, "test-chain") + oneHundredThreeTok, err := types.NewInternalERC20Token(math.NewInt(103), testERC20Address, "test-chain") require.NoError(t, err) exp := []*types.InternalOutgoingTransferTx{ { @@ -109,7 +111,7 @@ func TestAddToOutgoingPoolEdgeCases(t *testing.T) { require.NoError(t, e1) receiver, err := types.NewEthAddress(myReceiver) require.NoError(t, err) - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) @@ -119,7 +121,7 @@ func TestAddToOutgoingPoolEdgeCases(t *testing.T) { require.Zero(t, r) // mint some voucher first - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -131,7 +133,7 @@ func TestAddToOutgoingPoolEdgeCases(t *testing.T) { require.NoError(t, err) //////// Insufficient Balance from Amount //////// - badAmountToken, err := types.NewInternalERC20Token(sdk.NewInt(999999), testERC20Address, "test-chain") + badAmountToken, err := types.NewInternalERC20Token(math.NewInt(999999), testERC20Address, "test-chain") require.NoError(t, err) badAmount := sdk.NewCoin(testDenom, badAmountToken.Amount) r, err = input.GravityKeeper.AddToOutgoingPool(ctx, mySender, *receiver, badAmount, "test-chain") @@ -139,7 +141,7 @@ func TestAddToOutgoingPoolEdgeCases(t *testing.T) { require.Zero(t, r) //////// Zero inputs //////// - mtCtx := new(sdk.Context) + mtCtx := new(context.Context) mtSend := new(sdk.AccAddress) mtRecieve := types.ZeroAddress() // This address should not actually cause an issue mtCoin := new(sdk.Coin) @@ -163,7 +165,7 @@ func TestRemoveFromOutgoingPoolAndRefund(t *testing.T) { // mint some voucher first originalBal := uint64(99999) - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(originalBal), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewIntFromUint64(originalBal), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -182,7 +184,7 @@ func TestRemoveFromOutgoingPoolAndRefund(t *testing.T) { amountSum := uint64(0) amounts := []uint64{100, 101, 102, 103} for i, v := range amounts { - amountToken, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) amountSum += v @@ -241,7 +243,7 @@ func TestRemoveFromOutgoingPoolAndRefundCosmosOriginated(t *testing.T) { require.Equal(t, tokenAddr.GetAddress().Hex(), myTokenContractAddr) require.Equal(t, tokenAddr, addr) - allVouchers := sdk.Coins{sdk.NewCoin(myTokenDenom, sdk.NewIntFromUint64(originalBal))} + allVouchers := sdk.Coins{sdk.NewCoin(myTokenDenom, math.NewIntFromUint64(originalBal))} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) require.NoError(t, err) @@ -258,7 +260,7 @@ func TestRemoveFromOutgoingPoolAndRefundCosmosOriginated(t *testing.T) { ids := make([]uint64, 4) amounts := []uint64{100, 101, 102, 103} for i, v := range amounts { - amount := sdk.NewCoin(myTokenDenom, sdk.NewIntFromUint64(amounts[i])) + amount := sdk.NewCoin(myTokenDenom, math.NewIntFromUint64(amounts[i])) amountSum += v r, err := input.GravityKeeper.AddToOutgoingPool(ctx, mySender, *receiver, amount, "test-chain") @@ -294,7 +296,7 @@ func TestRemoveFromOutgoingPoolAndRefundCosmosOriginated(t *testing.T) { func checkRemovedTx( t *testing.T, input TestInput, - ctx sdk.Context, + ctx context.Context, id uint64, amount uint64, amountSum *uint64, @@ -337,7 +339,7 @@ func TestRefundInconsistentTx(t *testing.T) { require.NoError(t, e3) //////// Refund an inconsistent tx //////// - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(100), myTokenContractAddr.GetAddress().Hex(), "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(100), myTokenContractAddr.GetAddress().Hex(), "test-chain") require.NoError(t, err) // This unsafe override won't fail @@ -388,7 +390,7 @@ func TestRefundTwice(t *testing.T) { // mint some voucher first originalBal := uint64(99999) - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(originalBal), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewIntFromUint64(originalBal), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -399,7 +401,7 @@ func TestRefundTwice(t *testing.T) { err = input.BankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, mySender, allVouchers) require.NoError(t, err) - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(100), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(100), testERC20Address, "test-chain") require.NoError(t, err) origBalances := input.BankKeeper.GetAllBalances(ctx, mySender) @@ -438,7 +440,7 @@ func TestGetUnbatchedTransactions(t *testing.T) { tokenContract1, err := types.NewEthAddress(testERC20Address) require.NoError(t, err) // mint some vouchers first - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -453,7 +455,7 @@ func TestGetUnbatchedTransactions(t *testing.T) { amounts := []uint64{100, 101, 102, 103} idToTxMap := make(map[uint64]*types.OutgoingTransferTx) for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") require.NoError(t, err) amount1 := sdk.NewCoin(testDenom, amountToken.Amount) @@ -469,7 +471,7 @@ func TestGetUnbatchedTransactions(t *testing.T) { } // GetUnbatchedTxByAmountAndId - tokenAmount, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(amounts[0]), testERC20Address, "test-chain") + tokenAmount, err := types.NewInternalERC20Token(math.NewIntFromUint64(amounts[0]), testERC20Address, "test-chain") require.NoError(t, err) tokenId := ids[0] tx, err := input.GravityKeeper.GetUnbatchedTxByAmountAndId(ctx, *tokenAmount, tokenId) @@ -523,7 +525,7 @@ func TestIterateUnbatchedTransactions(t *testing.T) { tokenContract1, err := types.NewEthAddress(testERC20Address) require.NoError(t, err) // mint some vouchers first - token, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + token, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, token.Amount)} err = input.BankKeeper.MintCoins(ctx, types.ModuleName, allVouchers) @@ -538,7 +540,7 @@ func TestIterateUnbatchedTransactions(t *testing.T) { amounts := []uint64{100, 101, 102, 103} idToTxMap := make(map[uint64]*types.OutgoingTransferTx) for i := 0; i < 4; i++ { - amount1, err := types.NewInternalERC20Token(sdk.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") + amount1, err := types.NewInternalERC20Token(math.NewIntFromUint64(amounts[i]), testERC20Address, "test-chain") require.NoError(t, err) r, err := input.GravityKeeper.AddToOutgoingPool(ctx, mySender, *receiver, sdk.NewCoin(testDenom, amount1.Amount), "test-chain") require.NoError(t, err) @@ -600,7 +602,7 @@ func TestAddToOutgoingPoolExportGenesis(t *testing.T) { receiver, err := types.NewEthAddress(myReceiver) require.NoError(t, err) // mint some voucher first - allVouchersToken, err := types.NewInternalERC20Token(sdk.NewInt(99999), testERC20Address, "test-chain") + allVouchersToken, err := types.NewInternalERC20Token(math.NewInt(99999), testERC20Address, "test-chain") require.NoError(t, err) allVouchers := sdk.Coins{sdk.NewCoin(testDenom, allVouchersToken.Amount)} @@ -616,7 +618,7 @@ func TestAddToOutgoingPoolExportGenesis(t *testing.T) { foundTxsMap := make(map[uint64]bool) // when for i := 0; i < 4; i++ { - amountToken, err := types.NewInternalERC20Token(sdk.NewInt(int64(i+100)), testERC20Address, "test-chain") + amountToken, err := types.NewInternalERC20Token(math.NewInt(int64(i+100)), testERC20Address, "test-chain") require.NoError(t, err) amount := sdk.NewCoin(testDenom, amountToken.Amount) diff --git a/x/gravity/keeper/test_common.go b/x/gravity/keeper/test_common.go index 1e8114c2..3a3d98c5 100644 --- a/x/gravity/keeper/test_common.go +++ b/x/gravity/keeper/test_common.go @@ -1,15 +1,19 @@ package keeper import ( + "context" "crypto/ecdsa" "math/big" "testing" "time" - dbm "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + "cosmossdk.io/math" + "cosmossdk.io/store" + storetypes "cosmossdk.io/store/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" tmversion "github.com/cometbft/cometbft/proto/tendermint/version" + dbm "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -18,8 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" ccrypto "github.com/cosmos/cosmos-sdk/crypto/types" "github.com/cosmos/cosmos-sdk/std" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" @@ -58,10 +60,10 @@ import ( upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" - ibctransferkeeper "github.com/cosmos/ibc-go/v7/modules/apps/transfer/keeper" - ibctransfertypes "github.com/cosmos/ibc-go/v7/modules/apps/transfer/types" - ibcexported "github.com/cosmos/ibc-go/v7/modules/core/exported" - ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" + ibctransferkeeper "github.com/cosmos/ibc-go/v8/modules/apps/transfer/keeper" + ibctransfertypes "github.com/cosmos/ibc-go/v8/modules/apps/transfer/types" + ibcexported "github.com/cosmos/ibc-go/v8/modules/core/exported" + ibckeeper "github.com/cosmos/ibc-go/v8/modules/core/keeper" gethcommon "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" gravityparams "github.com/palomachain/paloma/app/params" @@ -237,7 +239,7 @@ var ( MaxEntries: 10, HistoricalEntries: 10000, BondDenom: testDenom, - MinCommissionRate: sdk.NewDecWithPrec(5, 2), + MinCommissionRate: math.LegacyNewDecWithPrec(5, 2), } // TestingGravityParams is a set of gravity params for testing @@ -249,8 +251,8 @@ var ( TargetBatchTimeout: 60001, AverageBlockTime: 5000, AverageEthereumBlockTime: 15000, - SlashFractionBatch: sdk.NewDecWithPrec(1, 2), - SlashFractionBadEthSignature: sdk.NewDecWithPrec(1, 2), + SlashFractionBatch: math.LegacyNewDecWithPrec(1, 2), + SlashFractionBadEthSignature: math.LegacyNewDecWithPrec(1, 2), } ) @@ -265,7 +267,7 @@ type TestInput struct { BankKeeper bankkeeper.BaseKeeper GovKeeper govkeeper.Keeper IbcTransferKeeper ibctransferkeeper.Keeper - Context sdk.Context + Context context.Context Marshaler codec.Codec LegacyAmino *codec.LegacyAmino GravityStoreKey *storetypes.KVStoreKey @@ -298,7 +300,7 @@ func addValidators(t *testing.T, input *TestInput, count int) { } // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, &input.StakingKeeper) + input.StakingKeeper.EndBlocker(input.Context) // Register eth addresses and orchestrator address for each validator for i, addr := range ValAddrs { @@ -306,12 +308,13 @@ func addValidators(t *testing.T, input *TestInput, count int) { require.NoError(t, err) validator, found := input.StakingKeeper.GetValidator(input.Context, addr) - require.True(t, found) + require.NoError(t, found) pubKey, err := validator.ConsPubKey() require.NoError(t, err) + valAddress := input.GravityKeeper.addressCodec.StringToBytes() - err = input.ValsetKeeper.AddExternalChainInfo(input.Context, validator.GetOperator(), []*valsettypes.ExternalChainInfo{ + err = input.ValsetKeeper.AddExternalChainInfo(input.Context, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", ChainReferenceID: "test-chain", @@ -328,7 +331,7 @@ func addValidators(t *testing.T, input *TestInput, count int) { } // SetupFiveValChain does all the initialization for a 5 Validator chain using the keys here -func SetupFiveValChain(t *testing.T) (TestInput, sdk.Context) { +func SetupFiveValChain(t *testing.T) (TestInput, context.Context) { t.Helper() input := CreateTestEnv(t) @@ -343,7 +346,7 @@ func SetupFiveValChain(t *testing.T) (TestInput, sdk.Context) { } // SetupTestChain sets up a test environment with the provided validator voting weights -func SetupTestChain(t *testing.T, weights []uint64) (TestInput, sdk.Context) { +func SetupTestChain(t *testing.T, weights []uint64) (TestInput, context.Context) { t.Helper() input, ctx := SetupFiveValChain(t) @@ -378,24 +381,25 @@ func SetupTestChain(t *testing.T, weights []uint64) (TestInput, sdk.Context) { // Create a validator for that account using some of the tokens in the account // and the staking handler - _, err := stakingMsgSvr.CreateValidator(sdk.WrapSDKContext(input.Context), NewTestMsgCreateValidator(valAddr, consPubKey, sdk.NewIntFromUint64(weight))) + _, err := stakingMsgSvr.CreateValidator(sdk.WrapSDKContext(input.Context), NewTestMsgCreateValidator(valAddr, consPubKey, math.NewIntFromUint64(weight))) require.NoError(t, err) // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, &input.StakingKeeper) + input.StakingKeeper.EndBlocker(input.Context) // increase block height by 100 blocks input.Context = input.Context.WithBlockHeight(input.Context.BlockHeight() + 100) // Run the staking endblocker to ensure valset is correct in state - staking.EndBlocker(input.Context, &input.StakingKeeper) + input.StakingKeeper.EndBlocker(input.Context) } // some inputs can cause the validator creation ot not work, this checks that // everything was successful. Adding 5 for the 5 validator initial setup - validators := input.StakingKeeper.GetBondedValidatorsByPower(input.Context) + validators, err := input.StakingKeeper.GetBondedValidatorsByPower(input.Context) + require.NoError(t, err) require.Equal(t, len(weights)+5, len(validators)) // Return the test input @@ -411,30 +415,30 @@ func CreateTestEnv(t *testing.T) TestInput { config.SetBech32PrefixForValidator("palomavaloper", "valoperpub") // Initialize store keys - gravityKey := sdk.NewKVStoreKey(types.StoreKey) - keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey) - keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey) - keyBank := sdk.NewKVStoreKey(banktypes.StoreKey) - keyDistro := sdk.NewKVStoreKey(distrtypes.StoreKey) - keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey) - keyGov := sdk.NewKVStoreKey(govtypes.StoreKey) - keySlashing := sdk.NewKVStoreKey(slashingtypes.StoreKey) - keyCapability := sdk.NewKVStoreKey(capabilitytypes.StoreKey) - keyUpgrade := sdk.NewKVStoreKey(upgradetypes.StoreKey) - keyIbc := sdk.NewKVStoreKey(ibcexported.StoreKey) - keyIbcTransfer := sdk.NewKVStoreKey(ibctransfertypes.StoreKey) - - keyValset := sdk.NewKVStoreKey(valsettypes.StoreKey) - memKeyValset := sdk.NewKVStoreKey(valsettypes.MemStoreKey) - keyConsensus := sdk.NewKVStoreKey(consensustypes.StoreKey) - memKeyConsensus := sdk.NewKVStoreKey(consensustypes.MemStoreKey) - keyEvm := sdk.NewKVStoreKey(evmtypes.StoreKey) - memKeyEvm := sdk.NewKVStoreKey(evmtypes.MemStoreKey) + gravityKey := storetypes.NewKVStoreKey(types.StoreKey) + keyAcc := storetypes.NewKVStoreKey(authtypes.StoreKey) + keyStaking := storetypes.NewKVStoreKey(stakingtypes.StoreKey) + keyBank := storetypes.NewKVStoreKey(banktypes.StoreKey) + keyDistro := storetypes.NewKVStoreKey(distrtypes.StoreKey) + keyParams := storetypes.NewKVStoreKey(paramstypes.StoreKey) + tkeyParams := storetypes.NewTransientStoreKey(paramstypes.TStoreKey) + keyGov := storetypes.NewKVStoreKey(govtypes.StoreKey) + keySlashing := storetypes.NewKVStoreKey(slashingtypes.StoreKey) + keyCapability := storetypes.NewKVStoreKey(capabilitytypes.StoreKey) + keyUpgrade := storetypes.NewKVStoreKey(upgradetypes.StoreKey) + keyIbc := storetypes.NewKVStoreKey(ibcexported.StoreKey) + keyIbcTransfer := storetypes.NewKVStoreKey(ibctransfertypes.StoreKey) + + keyValset := storetypes.NewKVStoreKey(valsettypes.StoreKey) + memKeyValset := storetypes.NewKVStoreKey(valsettypes.MemStoreKey) + keyConsensus := storetypes.NewKVStoreKey(consensustypes.StoreKey) + memKeyConsensus := storetypes.NewKVStoreKey(consensustypes.MemStoreKey) + keyEvm := storetypes.NewKVStoreKey(evmtypes.StoreKey) + memKeyEvm := storetypes.NewKVStoreKey(evmtypes.MemStoreKey) // Initialize memory database and mount stores on it db := dbm.NewMemDB() - ms := store.NewCommitMultiStore(db) + ms := store.NewCommitMultiStore(db, logger, storemetrics.NewNoOpMetrics()) ms.MountStoreWithDB(gravityKey, storetypes.StoreTypeIAVL, db) ms.MountStoreWithDB(keyAcc, storetypes.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, storetypes.StoreTypeIAVL, db) @@ -457,7 +461,7 @@ func CreateTestEnv(t *testing.T) TestInput { err := ms.LoadLatestVersion() require.Nil(t, err) - // Create sdk.Context + // Create context.Context ctx := sdk.NewContext(ms, tmproto.Header{ Version: tmversion.Consensus{ Block: 0, @@ -482,7 +486,7 @@ func CreateTestEnv(t *testing.T) TestInput { LastResultsHash: []byte{}, EvidenceHash: []byte{}, ProposerAddress: []byte{}, - }, false, log.TestingLogger()) + }, false, log.NewTestLogger(t)) cdc := MakeTestCodec() marshaler := MakeTestMarshaler() @@ -561,7 +565,7 @@ func CreateTestEnv(t *testing.T) TestInput { require.NoError(t, err) // set genesis items required for distribution - distKeeper.SetFeePool(ctx, distrtypes.InitialFeePool()) + distKeeper.FeePool.Set(ctx, distrtypes.InitialFeePool()) // set up initial accounts for name, perms := range maccPerms { @@ -576,7 +580,7 @@ func CreateTestEnv(t *testing.T) TestInput { // distribution module balance must be outstanding rewards + community pool in order to pass // invariants checks, therefore we must add any amount we add to the module balance to the fee pool feePool := distKeeper.GetFeePool(ctx) - newCoins := feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(amt...)...) + newCoins := feePool.CommunityPool.Add(math.LegacyNewDecCoinsFromCoins(amt...)...) feePool.CommunityPool = newCoins distKeeper.SetFeePool(ctx, feePool) @@ -589,7 +593,7 @@ func CreateTestEnv(t *testing.T) TestInput { moduleAcct := accountKeeper.GetAccount(ctx, stakeAddr) require.NotNil(t, moduleAcct) - bApp := *baseapp.NewBaseApp("test", log.TestingLogger(), db, MakeTestEncodingConfig().TxConfig.TxDecoder()) + bApp := *baseapp.NewBaseApp("test", log.NewTestLogger(t), db, MakeTestEncodingConfig().TxConfig.TxDecoder()) govKeeper := govkeeper.NewKeeper( marshaler, keyGov, @@ -620,7 +624,7 @@ func CreateTestEnv(t *testing.T) TestInput { authtypes.NewModuleAddress(govtypes.ModuleName).String(), ) - memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) + memKeys := storetypes.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) capabilityKeeper := *capabilitykeeper.NewKeeper( marshaler, keyCapability, @@ -851,7 +855,7 @@ func MakeTestEncodingConfig() gravityparams.EncodingConfig { } // MintVouchersFromAir creates new gravity vouchers given erc20tokens -func MintVouchersFromAir(t *testing.T, ctx sdk.Context, k Keeper, dest sdk.AccAddress, amount types.InternalERC20Token) sdk.Coin { +func MintVouchersFromAir(t *testing.T, ctx context.Context, k Keeper, dest sdk.AccAddress, amount types.InternalERC20Token) sdk.Coin { coin := sdk.NewCoin(testDenom, amount.Amount) vouchers := sdk.Coins{coin} err := k.bankKeeper.MintCoins(ctx, types.ModuleName, vouchers) @@ -861,17 +865,17 @@ func MintVouchersFromAir(t *testing.T, ctx sdk.Context, k Keeper, dest sdk.AccAd return coin } -func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey ccrypto.PubKey, amt sdk.Int) *stakingtypes.MsgCreateValidator { - commission := stakingtypes.NewCommissionRates(sdk.NewDecWithPrec(1, 1), sdk.NewDecWithPrec(2, 1), sdk.NewDecWithPrec(5, 3)) +func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey ccrypto.PubKey, amt math.Int) *stakingtypes.MsgCreateValidator { + commission := stakingtypes.NewCommissionRates(math.LegacyNewDecWithPrec(1, 1), math.LegacyNewDecWithPrec(2, 1), math.LegacyNewDecWithPrec(5, 3)) out, err := stakingtypes.NewMsgCreateValidator( - address, pubKey, sdk.NewCoin(testDenom, amt), + address.String(), pubKey, sdk.NewCoin(testDenom, amt), stakingtypes.Description{ Moniker: "", Identity: "", Website: "", SecurityContact: "", Details: "", - }, commission, sdk.OneInt(), + }, commission, math.OneInt(), ) if err != nil { panic(err) @@ -879,7 +883,7 @@ func NewTestMsgCreateValidator(address sdk.ValAddress, pubKey ccrypto.PubKey, am return out } -func NewTestMsgUnDelegateValidator(address sdk.ValAddress, amt sdk.Int) *stakingtypes.MsgUndelegate { - msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(address), address, sdk.NewCoin(testDenom, amt)) +func NewTestMsgUnDelegateValidator(address sdk.ValAddress, amt math.Int) *stakingtypes.MsgUndelegate { + msg := stakingtypes.NewMsgUndelegate(sdk.AccAddress(address).String(), address.String(), sdk.NewCoin(testDenom, amt)) return msg } diff --git a/x/gravity/module.go b/x/gravity/module.go index a2c72668..2c62dcf8 100644 --- a/x/gravity/module.go +++ b/x/gravity/module.go @@ -1,9 +1,11 @@ package gravity import ( + "context" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -22,8 +24,20 @@ import ( // type check to ensure the interface is properly implemented // nolint: exhaustruct var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + // _ module.AppModule = AppModule{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.HasServices = AppModule{} + _ module.AppModuleGenesis = AppModule{} + _ module.AppModuleSimulation = AppModule{} + _ module.HasABCIGenesis = AppModule{} + _ module.HasConsensusVersion = AppModule{} + _ module.HasInvariants = AppModule{} + _ module.HasName = AppModule{} + _ module.HasGenesisBasics = AppModule{} + _ module.HasProposalContents = AppModule{} + _ appmodule.HasEndBlocker = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} + _ appmodule.AppModule = AppModule{} ) // AppModuleBasic object for module implementation @@ -92,6 +106,8 @@ type AppModule struct { bankKeeper bankkeeper.Keeper } +func (m AppModule) IsOnePerModuleType() {} +func (m AppModule) IsAppModule() {} func (am AppModule) ConsensusVersion() uint64 { return 4 } @@ -141,12 +157,15 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw } // BeginBlock implements app module -func (am AppModule) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock) {} +func (am AppModule) BeginBlock(ctx context.Context) error { + return nil +} // EndBlock implements app module -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - EndBlocker(ctx, am.keeper) - return []abci.ValidatorUpdate{} +func (am AppModule) EndBlock(ctx context.Context) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + EndBlocker(sdkCtx, am.keeper) + return nil } //____________________________________________________________________________ @@ -167,7 +186,7 @@ func (am AppModule) ProposalContents(simState module.SimulationState) []simtypes } // RegisterStoreDecoder registers a decoder for distribution module's types -func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { +func (am AppModule) RegisterStoreDecoder(sdr simtypes.StoreDecoderRegistry) { // TODO: implement gravity simulation stuffs // sdr[types.StoreKey] = simulation.NewDecodeStore(am.cdc) } diff --git a/x/gravity/types/attestation.go b/x/gravity/types/attestation.go index bd73c6fd..f91ef414 100644 --- a/x/gravity/types/attestation.go +++ b/x/gravity/types/attestation.go @@ -1,10 +1,10 @@ package types import ( + sdkerrors "cosmossdk.io/errors" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/gogo/protobuf/proto" ) diff --git a/x/gravity/types/attestation.pb.go b/x/gravity/types/attestation.pb.go index 1aadf06f..4f0fa4fb 100644 --- a/x/gravity/types/attestation.pb.go +++ b/x/gravity/types/attestation.pb.go @@ -4,9 +4,9 @@ package types import ( + cosmossdk_io_math "cosmossdk.io/math" fmt "fmt" types "github.com/cosmos/cosmos-sdk/codec/types" - github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" io "io" @@ -147,9 +147,9 @@ func (m *Attestation) GetClaim() *types.Any { // originated token, if so it will be the ERC20 address of the representation // (note: developers should look up the token symbol using the address on ETH to display for UI) type ERC20Token struct { - Contract string `protobuf:"bytes,1,opt,name=contract,proto3" json:"contract,omitempty"` - Amount github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"amount"` - ChainReferenceId string `protobuf:"bytes,3,opt,name=chain_reference_id,json=chainReferenceId,proto3" json:"chain_reference_id,omitempty"` + Contract string `protobuf:"bytes,1,opt,name=contract,proto3" json:"contract,omitempty"` + Amount cosmossdk_io_math.Int `protobuf:"bytes,2,opt,name=amount,proto3,customtype=cosmossdk.io/math.Int" json:"amount"` + ChainReferenceId string `protobuf:"bytes,3,opt,name=chain_reference_id,json=chainReferenceId,proto3" json:"chain_reference_id,omitempty"` } func (m *ERC20Token) Reset() { *m = ERC20Token{} } @@ -486,47 +486,47 @@ func init() { } var fileDescriptor_05057dba69344365 = []byte{ - // 629 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0xcd, 0x4e, 0xdb, 0x40, - 0x10, 0x8e, 0x43, 0x40, 0x64, 0x11, 0x90, 0xae, 0x10, 0x0a, 0x56, 0x6b, 0xa2, 0x48, 0xa5, 0x29, - 0x02, 0xbb, 0xa2, 0x4f, 0x10, 0x82, 0x29, 0x96, 0xf8, 0x89, 0x16, 0x57, 0x55, 0x7b, 0xb1, 0x36, - 0xf6, 0xe2, 0x58, 0x24, 0xbb, 0x91, 0xbd, 0x58, 0xe4, 0xd2, 0x4b, 0x2f, 0x3d, 0xf6, 0x09, 0x7a, - 0xe9, 0xcb, 0x20, 0xf5, 0xc2, 0xb1, 0xea, 0x01, 0x55, 0xf0, 0x22, 0x95, 0x77, 0x37, 0x66, 0xa5, - 0xb6, 0xb7, 0x9e, 0xbc, 0xdf, 0xcc, 0xf8, 0x9b, 0xef, 0x9b, 0xf1, 0x1a, 0xec, 0x4c, 0xf0, 0x88, - 0x8d, 0x71, 0x38, 0xc4, 0x09, 0x75, 0xe4, 0xd9, 0x89, 0x53, 0x9c, 0x27, 0x7c, 0xea, 0x60, 0xce, - 0x49, 0xc6, 0x31, 0x4f, 0x18, 0xb5, 0x27, 0x29, 0xe3, 0x0c, 0x9a, 0x5a, 0xb5, 0x2d, 0xcf, 0xb6, - 0xaa, 0x36, 0xd7, 0x62, 0x16, 0x33, 0x51, 0xe6, 0x14, 0x27, 0xf9, 0x86, 0xb9, 0x11, 0x33, 0x16, - 0x8f, 0x88, 0x23, 0xd0, 0xe0, 0xea, 0xc2, 0xc1, 0x74, 0x2a, 0x53, 0xed, 0x4f, 0x06, 0x58, 0xea, - 0x3e, 0xb6, 0x80, 0x26, 0x58, 0x64, 0x83, 0x8c, 0xa4, 0x39, 0x89, 0x9a, 0x46, 0xcb, 0xe8, 0x2c, - 0xa2, 0x12, 0xc3, 0x35, 0x30, 0x9f, 0x33, 0x4e, 0xb2, 0x66, 0xb5, 0x35, 0xd7, 0xa9, 0x23, 0x09, - 0xe0, 0x3a, 0x58, 0x18, 0x92, 0x24, 0x1e, 0xf2, 0xe6, 0x5c, 0xcb, 0xe8, 0xd4, 0x90, 0x42, 0x70, - 0x1b, 0xcc, 0x87, 0x23, 0x9c, 0x8c, 0x9b, 0xb5, 0x96, 0xd1, 0x59, 0xda, 0x5b, 0xb3, 0xa5, 0x08, - 0x7b, 0x26, 0xc2, 0xee, 0xd2, 0x29, 0x92, 0x25, 0xed, 0xaf, 0x06, 0x00, 0x2e, 0xea, 0xed, 0xbd, - 0xf2, 0xd9, 0x25, 0x11, 0x22, 0x42, 0x46, 0x79, 0x8a, 0x43, 0x2e, 0x44, 0xd4, 0x51, 0x89, 0xe1, - 0x21, 0x58, 0xc0, 0x63, 0x76, 0x45, 0x79, 0xb3, 0x5a, 0x64, 0xf6, 0xed, 0x9b, 0xbb, 0xcd, 0xca, - 0xcf, 0xbb, 0xcd, 0xad, 0x38, 0xe1, 0xc3, 0xab, 0x81, 0x1d, 0xb2, 0xb1, 0x13, 0xb2, 0x6c, 0xcc, - 0x32, 0xf5, 0xd8, 0xcd, 0xa2, 0x4b, 0x87, 0x4f, 0x27, 0x24, 0xb3, 0x3d, 0xca, 0x91, 0x7a, 0x1b, - 0xee, 0x00, 0x28, 0x26, 0x18, 0xa4, 0xe4, 0x82, 0xa4, 0x84, 0x86, 0x24, 0x48, 0x22, 0x61, 0xa1, - 0x8e, 0x1a, 0x22, 0x83, 0x66, 0x09, 0x2f, 0x6a, 0x7f, 0x37, 0x40, 0xc3, 0xcd, 0x09, 0xe5, 0x67, - 0x62, 0x18, 0x72, 0x56, 0x2f, 0x41, 0x43, 0xdb, 0x4e, 0x50, 0xf4, 0x50, 0x72, 0x57, 0xb5, 0xb8, - 0x3f, 0x9d, 0x10, 0xf8, 0x02, 0xac, 0x0e, 0xd2, 0x24, 0x8a, 0x49, 0x50, 0x1a, 0x13, 0xf2, 0xd1, - 0x8a, 0x0c, 0xf7, 0x66, 0xf6, 0xb6, 0x1e, 0x0b, 0x85, 0xba, 0x52, 0xd3, 0xb2, 0x2a, 0x2c, 0xa2, - 0x5e, 0x04, 0x9f, 0x83, 0x15, 0xbd, 0x77, 0x12, 0x89, 0x31, 0xd7, 0xd1, 0xb2, 0x16, 0xf5, 0xc4, - 0xca, 0x28, 0xa3, 0x21, 0x69, 0xce, 0x8b, 0xac, 0x04, 0xed, 0x8f, 0xa0, 0x25, 0xcc, 0x78, 0x34, - 0xc7, 0xa3, 0x24, 0x3a, 0x27, 0x34, 0xf2, 0x59, 0x5f, 0x7c, 0x49, 0x88, 0x84, 0x24, 0xc9, 0x49, - 0x5a, 0xac, 0x55, 0xcd, 0x59, 0x5a, 0x9a, 0xcd, 0xad, 0x64, 0xac, 0x6a, 0x8c, 0x45, 0x94, 0x17, - 0xab, 0x53, 0x62, 0x25, 0x28, 0x38, 0x32, 0x42, 0x23, 0x92, 0x2a, 0x71, 0x0a, 0xb5, 0xdf, 0x81, - 0x27, 0xa2, 0xbf, 0xde, 0xf8, 0x7f, 0x34, 0x6c, 0x5f, 0x83, 0xf5, 0x3f, 0x88, 0x8f, 0x59, 0x88, - 0x47, 0x8f, 0x2c, 0x86, 0xce, 0x62, 0x82, 0xc5, 0x54, 0x19, 0x56, 0xf4, 0x25, 0xfe, 0xb7, 0x25, - 0xa5, 0xb2, 0xa6, 0xab, 0xdc, 0xa6, 0xa0, 0xde, 0x2b, 0x3e, 0x65, 0xb1, 0x6d, 0x13, 0xac, 0xf7, - 0x8e, 0xbb, 0xde, 0x49, 0xe0, 0xbf, 0xef, 0xbb, 0xc1, 0xdb, 0xd3, 0xf3, 0xbe, 0xdb, 0xf3, 0x0e, - 0x3d, 0xf7, 0xa0, 0x51, 0x81, 0xcf, 0xc0, 0x86, 0x96, 0x3b, 0x77, 0x4f, 0x0f, 0x02, 0xff, 0x2c, - 0xe8, 0x77, 0x8f, 0xcf, 0x4e, 0xba, 0x0d, 0x03, 0xb6, 0xc0, 0x53, 0x2d, 0xbd, 0xdf, 0xf5, 0x7b, - 0x47, 0x65, 0x91, 0xeb, 0x1f, 0x35, 0xaa, 0x66, 0xed, 0xf3, 0x37, 0xab, 0xb2, 0xff, 0xe6, 0xe6, - 0xde, 0x32, 0x6e, 0xef, 0x2d, 0xe3, 0xd7, 0xbd, 0x65, 0x7c, 0x79, 0xb0, 0x2a, 0xb7, 0x0f, 0x56, - 0xe5, 0xc7, 0x83, 0x55, 0xf9, 0xb0, 0xab, 0x5d, 0x84, 0xbf, 0xfc, 0x57, 0xae, 0xcb, 0x3f, 0x8b, - 0xb8, 0x13, 0x83, 0x05, 0x71, 0x1f, 0x5f, 0xff, 0x0e, 0x00, 0x00, 0xff, 0xff, 0xe5, 0x88, 0xc6, - 0x72, 0x84, 0x04, 0x00, 0x00, + // 628 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x54, 0x4f, 0x6f, 0xd3, 0x30, + 0x14, 0x6f, 0xba, 0x6e, 0x5a, 0x3d, 0x6d, 0x2b, 0xd6, 0x98, 0xba, 0x88, 0x65, 0x55, 0x25, 0xa0, + 0x4c, 0x23, 0x41, 0x43, 0x7c, 0x80, 0xae, 0x0b, 0x2c, 0xd2, 0xfe, 0x54, 0x5e, 0x10, 0x82, 0x4b, + 0xe4, 0x26, 0x5e, 0x6a, 0xad, 0xb5, 0xab, 0xc4, 0x8b, 0xd6, 0x0b, 0x17, 0x2e, 0x5c, 0x90, 0xf8, + 0x0e, 0x7c, 0x99, 0x49, 0x5c, 0x76, 0x44, 0x1c, 0x26, 0xb4, 0x7d, 0x11, 0x14, 0xdb, 0xcd, 0x22, + 0x01, 0x37, 0x6e, 0xfe, 0xbd, 0xf7, 0xcb, 0x7b, 0xbf, 0xdf, 0x7b, 0x8e, 0xc1, 0xce, 0x04, 0x8f, + 0xf8, 0x18, 0x87, 0x43, 0x4c, 0x99, 0xa3, 0xce, 0x4e, 0x9c, 0xe0, 0x8c, 0x8a, 0xa9, 0x83, 0x85, + 0x20, 0xa9, 0xc0, 0x82, 0x72, 0x66, 0x4f, 0x12, 0x2e, 0x38, 0x34, 0x4b, 0x6c, 0x5b, 0x9d, 0x6d, + 0xcd, 0x36, 0xd7, 0x62, 0x1e, 0x73, 0x49, 0x73, 0xf2, 0x93, 0xfa, 0xc2, 0xdc, 0x88, 0x39, 0x8f, + 0x47, 0xc4, 0x91, 0x68, 0x70, 0x71, 0xe6, 0x60, 0x36, 0x55, 0xa9, 0xf6, 0x27, 0x03, 0x2c, 0x75, + 0xef, 0x5b, 0x40, 0x13, 0x2c, 0xf2, 0x41, 0x4a, 0x92, 0x8c, 0x44, 0x4d, 0xa3, 0x65, 0x74, 0x16, + 0x51, 0x81, 0xe1, 0x1a, 0x98, 0xcf, 0xb8, 0x20, 0x69, 0xb3, 0xda, 0x9a, 0xeb, 0xd4, 0x91, 0x02, + 0x70, 0x1d, 0x2c, 0x0c, 0x09, 0x8d, 0x87, 0xa2, 0x39, 0xd7, 0x32, 0x3a, 0x35, 0xa4, 0x11, 0xdc, + 0x06, 0xf3, 0xe1, 0x08, 0xd3, 0x71, 0xb3, 0xd6, 0x32, 0x3a, 0x4b, 0xbb, 0x6b, 0xb6, 0x12, 0x61, + 0xcf, 0x44, 0xd8, 0x5d, 0x36, 0x45, 0x8a, 0xd2, 0xfe, 0x62, 0x00, 0xe0, 0xa2, 0xde, 0xee, 0x0b, + 0x9f, 0x9f, 0x13, 0x29, 0x22, 0xe4, 0x4c, 0x24, 0x38, 0x14, 0x52, 0x44, 0x1d, 0x15, 0x18, 0xbe, + 0x02, 0x0b, 0x78, 0xcc, 0x2f, 0x98, 0x68, 0x56, 0xf3, 0xcc, 0xde, 0xe6, 0xd5, 0xcd, 0x56, 0xe5, + 0xe7, 0xcd, 0xd6, 0xc3, 0x90, 0xa7, 0x63, 0x9e, 0xa6, 0xd1, 0xb9, 0x4d, 0xb9, 0x33, 0xc6, 0x62, + 0x68, 0x7b, 0x4c, 0x20, 0x4d, 0x86, 0x3b, 0x00, 0xca, 0x81, 0x05, 0x09, 0x39, 0x23, 0x09, 0x61, + 0x21, 0x09, 0x68, 0x24, 0x15, 0xd7, 0x51, 0x43, 0x66, 0xd0, 0x2c, 0xe1, 0x45, 0xed, 0xef, 0x06, + 0x68, 0xb8, 0x19, 0x61, 0xe2, 0x44, 0x7a, 0x57, 0xa3, 0x79, 0x06, 0x1a, 0xa5, 0x65, 0x04, 0x62, + 0x3a, 0x21, 0x5a, 0xdd, 0x6a, 0x29, 0xee, 0x4f, 0x27, 0x04, 0x3e, 0x05, 0xab, 0x83, 0x84, 0x46, + 0x31, 0x09, 0x0a, 0x1f, 0x52, 0x2d, 0x5a, 0x51, 0xe1, 0xde, 0xcc, 0xcd, 0x93, 0x7b, 0xa2, 0x54, + 0x57, 0x68, 0x5a, 0xd6, 0xc4, 0x3c, 0xea, 0x45, 0xf0, 0x31, 0x58, 0x29, 0xf7, 0xa6, 0x91, 0x9c, + 0x6a, 0x1d, 0x2d, 0x97, 0xa2, 0x9e, 0xdc, 0x10, 0xe3, 0x2c, 0x24, 0xcd, 0x79, 0x99, 0x55, 0xa0, + 0xfd, 0x11, 0xb4, 0xa4, 0x19, 0x8f, 0x65, 0x78, 0x44, 0xa3, 0x53, 0xc2, 0x22, 0x9f, 0xf7, 0xe5, + 0xc5, 0x41, 0x24, 0x24, 0x34, 0x23, 0x49, 0xbe, 0x45, 0x3d, 0x56, 0x65, 0x69, 0x36, 0xb7, 0xa2, + 0x62, 0xb5, 0x54, 0x31, 0x8f, 0x8a, 0x7c, 0x53, 0x5a, 0xac, 0x02, 0x79, 0x8d, 0x94, 0xb0, 0x88, + 0x24, 0x5a, 0x9c, 0x46, 0xed, 0x77, 0xe0, 0x81, 0xec, 0x5f, 0x6e, 0xfc, 0x3f, 0x1a, 0xb6, 0x2f, + 0xc1, 0xfa, 0x1f, 0x85, 0x0f, 0x79, 0x88, 0x47, 0xf7, 0x55, 0x8c, 0x72, 0x15, 0x13, 0x2c, 0x26, + 0xda, 0xb0, 0x2e, 0x5f, 0xe0, 0x7f, 0x5b, 0xd2, 0x2a, 0x6b, 0x65, 0x95, 0xdb, 0x0c, 0xd4, 0x7b, + 0xf9, 0xcd, 0x95, 0xdb, 0x36, 0xc1, 0x7a, 0xef, 0xb0, 0xeb, 0x1d, 0x05, 0xfe, 0xfb, 0xbe, 0x1b, + 0xbc, 0x3d, 0x3e, 0xed, 0xbb, 0x3d, 0xef, 0xb5, 0xe7, 0xee, 0x37, 0x2a, 0x70, 0x13, 0x6c, 0x94, + 0x72, 0xa7, 0xee, 0xf1, 0x7e, 0xe0, 0x9f, 0x04, 0xfd, 0xee, 0xe1, 0xc9, 0x51, 0xb7, 0x61, 0xc0, + 0x16, 0x78, 0x54, 0x4a, 0xef, 0x75, 0xfd, 0xde, 0x41, 0x41, 0x72, 0xfd, 0x83, 0x46, 0xd5, 0xac, + 0x7d, 0xfe, 0x66, 0x55, 0xf6, 0xde, 0x5c, 0xdd, 0x5a, 0xc6, 0xf5, 0xad, 0x65, 0xfc, 0xba, 0xb5, + 0x8c, 0xaf, 0x77, 0x56, 0xe5, 0xfa, 0xce, 0xaa, 0xfc, 0xb8, 0xb3, 0x2a, 0x1f, 0x9e, 0xc7, 0x54, + 0x0c, 0x2f, 0x06, 0x76, 0xc8, 0xc7, 0xce, 0x5f, 0x9e, 0x91, 0xcb, 0xe2, 0x21, 0xc9, 0xef, 0x6b, + 0x3a, 0x58, 0x90, 0xbf, 0xdf, 0xcb, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xce, 0xe8, 0xed, 0xf3, + 0x73, 0x04, 0x00, 0x00, } func (m *Attestation) Marshal() (dAtA []byte, err error) { diff --git a/x/gravity/types/batch_test.go b/x/gravity/types/batch_test.go index b41a2d9e..7d076fc0 100644 --- a/x/gravity/types/batch_test.go +++ b/x/gravity/types/batch_test.go @@ -4,6 +4,7 @@ import ( "encoding/hex" "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -25,7 +26,7 @@ func TestOutgoingTxBatchCheckpoint(t *testing.T) { Sender: "paloma1rxdhpk85wju9z9kqf6m0wq0rkty7gpjhey4wd2", DestAddress: "0xE3cD54d29CBf35648EDcf53D6a344bd4B88DA059", Erc20Token: ERC20Token{ - Amount: sdk.NewInt(10000000), + Amount: math.NewInt(10000000), Contract: "0x28E9e9bfedEd29747FCc33ccA25b4B75f05E434B", ChainReferenceId: "bnb-main", }, diff --git a/x/gravity/types/ethereum.go b/x/gravity/types/ethereum.go index f72f5887..10759318 100644 --- a/x/gravity/types/ethereum.go +++ b/x/gravity/types/ethereum.go @@ -6,8 +6,10 @@ import ( "fmt" "strings" + sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "github.com/cosmos/cosmos-sdk/types/errors" gethcommon "github.com/ethereum/go-ethereum/common" ) @@ -99,11 +101,11 @@ func EthAddrLessThan(e EthAddress, o EthAddress) bool { // NewERC20Token returns a new instance of an ERC20 func NewERC20Token(amount uint64, contract string, chainReferenceId string) ERC20Token { - return NewSDKIntERC20Token(sdk.NewIntFromUint64(amount), contract, chainReferenceId) + return NewSDKIntERC20Token(math.NewIntFromUint64(amount), contract, chainReferenceId) } // NewSDKIntERC20Token returns a new instance of an ERC20, accepting a sdk.Int -func NewSDKIntERC20Token(amount sdk.Int, contract string, chainReferenceId string) ERC20Token { +func NewSDKIntERC20Token(amount math.Int, contract string, chainReferenceId string) ERC20Token { return ERC20Token{ Amount: amount, Contract: contract, @@ -118,13 +120,13 @@ func (e ERC20Token) ToInternal() (*InternalERC20Token, error) { // InternalERC20Token contains validated fields, used for all internal computation type InternalERC20Token struct { - Amount sdk.Int + Amount math.Int Contract EthAddress ChainReferenceID string } // NewInternalERC20Token creates an InternalERC20Token, performing validation and returning any errors -func NewInternalERC20Token(amount sdk.Int, contract string, chainReferenceId string) (*InternalERC20Token, error) { +func NewInternalERC20Token(amount math.Int, contract string, chainReferenceId string) (*InternalERC20Token, error) { ethAddress, err := NewEthAddress(contract) if err != nil { // ethAddress could be nil, must return here return nil, sdkerrors.Wrap(err, "invalid contract") @@ -144,7 +146,7 @@ func NewInternalERC20Token(amount sdk.Int, contract string, chainReferenceId str // ValidateBasic performs validation on all fields of an InternalERC20Token func (i *InternalERC20Token) ValidateBasic() error { if i.Amount.IsNegative() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "coins must not be negative") + return sdkerrors.Wrap(errorsmod.ErrInvalidCoins, "coins must not be negative") } err := i.Contract.ValidateBasic() if err != nil { diff --git a/x/gravity/types/expected_keepers.go b/x/gravity/types/expected_keepers.go index c6c5dc9a..bfb5055e 100644 --- a/x/gravity/types/expected_keepers.go +++ b/x/gravity/types/expected_keepers.go @@ -1,13 +1,14 @@ package types import ( + context "context" "time" "cosmossdk.io/math" + + storetypes "cosmossdk.io/store/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" bank "github.com/cosmos/cosmos-sdk/x/bank/types" - distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" xchain "github.com/palomachain/paloma/internal/x-chain" @@ -16,60 +17,58 @@ import ( // StakingKeeper defines the expected staking keeper methods type StakingKeeper interface { - GetBondedValidatorsByPower(ctx sdk.Context) []stakingtypes.Validator - GetLastValidatorPower(ctx sdk.Context, operator sdk.ValAddress) int64 - GetLastTotalPower(ctx sdk.Context) (power sdk.Int) - IterateValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - ValidatorQueueIterator(ctx sdk.Context, endTime time.Time, endHeight int64) sdk.Iterator - GetParams(ctx sdk.Context) stakingtypes.Params - GetValidator(ctx sdk.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found bool) - IterateBondedValidatorsByPower(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - IterateLastValidators(sdk.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - Validator(sdk.Context, sdk.ValAddress) stakingtypes.ValidatorI - ValidatorByConsAddr(sdk.Context, sdk.ConsAddress) stakingtypes.ValidatorI - Slash(ctx sdk.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor sdk.Dec) math.Int - Jail(sdk.Context, sdk.ConsAddress) + GetBondedValidatorsByPower(ctx context.Context) ([]stakingtypes.Validator, error) + GetLastValidatorPower(ctx context.Context, operator sdk.ValAddress) (int64, error) + GetLastTotalPower(ctx context.Context) (math.Int, error) + IterateValidators(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error + ValidatorQueueIterator(ctx context.Context, endTime time.Time, endHeight int64) (storetypes.Iterator, error) + GetParams(ctx context.Context) (stakingtypes.Params, error) + GetValidator(ctx context.Context, addr sdk.ValAddress) (validator stakingtypes.Validator, found error) + IterateBondedValidatorsByPower(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error + IterateLastValidators(context.Context, func(index int64, validator stakingtypes.ValidatorI) (stop bool)) error + Validator(context.Context, sdk.ValAddress) (stakingtypes.ValidatorI, error) + ValidatorByConsAddr(context.Context, sdk.ConsAddress) (stakingtypes.ValidatorI, error) + Slash(ctx context.Context, consAddr sdk.ConsAddress, infractionHeight int64, power int64, slashFactor math.LegacyDec) (math.Int, error) + Jail(context.Context, sdk.ConsAddress) error } // BankKeeper defines the expected bank keeper methods type BankKeeper interface { - GetSupply(ctx sdk.Context, denom string) sdk.Coin - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - SendCoinsFromModuleToModule(ctx sdk.Context, senderModule string, recipientModule string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, name string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, name string, amt sdk.Coins) error - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins - GetDenomMetaData(ctx sdk.Context, denom string) (bank.Metadata, bool) - SetDenomMetaData(ctx sdk.Context, denomMetaData bank.Metadata) - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - IsSendEnabledCoins(ctx sdk.Context, coins ...sdk.Coin) error - SendCoins(ctx sdk.Context, from, to sdk.AccAddress, amt sdk.Coins) error + GetSupply(ctx context.Context, denom string) sdk.Coin + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToModule(ctx context.Context, senderModule string, recipientModule string, amt sdk.Coins) error + MintCoins(ctx context.Context, name string, amt sdk.Coins) error + BurnCoins(ctx context.Context, name string, amt sdk.Coins) error + GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins + GetDenomMetaData(ctx context.Context, denom string) (bank.Metadata, bool) + SetDenomMetaData(ctx context.Context, denomMetaData bank.Metadata) + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + IsSendEnabledCoins(ctx context.Context, coins ...sdk.Coin) error + SendCoins(ctx context.Context, from, to sdk.AccAddress, amt sdk.Coins) error } type SlashingKeeper interface { - GetValidatorSigningInfo(ctx sdk.Context, address sdk.ConsAddress) (info slashingtypes.ValidatorSigningInfo, found bool) + GetValidatorSigningInfo(ctx context.Context, address sdk.ConsAddress) (info slashingtypes.ValidatorSigningInfo, found error) } // AccountKeeper defines the interface contract required for account // functionality. type AccountKeeper interface { - GetSequence(ctx sdk.Context, addr sdk.AccAddress) (uint64, error) - NewAccountWithAddress(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + GetSequence(ctx context.Context, addr sdk.AccAddress) (uint64, error) + NewAccountWithAddress(ctx context.Context, addr sdk.AccAddress) sdk.AccountI GetModuleAddress(moduleName string) sdk.AccAddress - GetModuleAccount(ctx sdk.Context, moduleName string) types.ModuleAccountI - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + GetModuleAccount(ctx context.Context, moduleName string) sdk.ModuleAccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI } type DistributionKeeper interface { - FundCommunityPool(ctx sdk.Context, amount sdk.Coins, sender sdk.AccAddress) error - GetFeePool(ctx sdk.Context) (feePool distributiontypes.FeePool) - SetFeePool(ctx sdk.Context, feePool distributiontypes.FeePool) + FundCommunityPool(ctx context.Context, amount sdk.Coins, sender sdk.AccAddress) error } type EVMKeeper interface { - GetChainInfo(ctx sdk.Context, targetChainReferenceID string) (*evmtypes.ChainInfo, error) - PickValidatorForMessage(ctx sdk.Context, chainReferenceID string, requirements *xchain.JobRequirements) (string, error) - GetEthAddressByValidator(ctx sdk.Context, validator sdk.ValAddress, chainReferenceId string) (ethAddress *EthAddress, found bool, err error) - GetValidatorAddressByEthAddress(ctx sdk.Context, ethAddr EthAddress, chainReferenceId string) (valAddr sdk.ValAddress, found bool, err error) + GetChainInfo(ctx context.Context, targetChainReferenceID string) (*evmtypes.ChainInfo, error) + PickValidatorForMessage(ctx context.Context, chainReferenceID string, requirements *xchain.JobRequirements) (string, error) + GetEthAddressByValidator(ctx context.Context, validator sdk.ValAddress, chainReferenceId string) (ethAddress *EthAddress, found bool, err error) + GetValidatorAddressByEthAddress(ctx context.Context, ethAddr EthAddress, chainReferenceId string) (valAddr sdk.ValAddress, found bool, err error) } diff --git a/x/gravity/types/genesis.go b/x/gravity/types/genesis.go index a89ac9ea..be975a80 100644 --- a/x/gravity/types/genesis.go +++ b/x/gravity/types/genesis.go @@ -5,8 +5,8 @@ import ( "fmt" "strings" - sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" + "cosmossdk.io/math" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" ) @@ -18,7 +18,7 @@ const ( var ( // AttestationVotesPowerThreshold threshold of votes power to succeed - AttestationVotesPowerThreshold = sdk.NewInt(66) + AttestationVotesPowerThreshold = math.NewInt(66) // ParamsStoreKeyContractHash stores the contract hash ParamsStoreKeyContractHash = []byte("ContractHash") @@ -62,8 +62,8 @@ var ( TargetBatchTimeout: 0, AverageBlockTime: 0, AverageEthereumBlockTime: 0, - SlashFractionBatch: sdk.Dec{}, - SlashFractionBadEthSignature: sdk.Dec{}, + SlashFractionBatch: math.LegacyDec{}, + SlashFractionBadEthSignature: math.LegacyDec{}, } ) @@ -100,8 +100,8 @@ func DefaultParams() *Params { TargetBatchTimeout: 43200000, AverageBlockTime: 5000, AverageEthereumBlockTime: 15000, - SlashFractionBatch: sdk.NewDec(1).Quo(sdk.NewDec(1000)), - SlashFractionBadEthSignature: sdk.NewDec(1).Quo(sdk.NewDec(1000)), + SlashFractionBatch: math.LegacyNewDec(1).Quo(math.LegacyNewDec(1000)), + SlashFractionBadEthSignature: math.LegacyNewDec(1).Quo(math.LegacyNewDec(1000)), } } @@ -147,8 +147,8 @@ func ParamKeyTable() paramtypes.KeyTable { TargetBatchTimeout: 0, AverageBlockTime: 0, AverageEthereumBlockTime: 0, - SlashFractionBatch: sdk.Dec{}, - SlashFractionBadEthSignature: sdk.Dec{}, + SlashFractionBatch: math.LegacyDec{}, + SlashFractionBadEthSignature: math.LegacyDec{}, }) } @@ -245,7 +245,7 @@ func validateSignedBatchesWindow(i interface{}) error { func validateSlashFractionBatch(i interface{}) error { // TODO: do we want to set some bounds on this value? - if _, ok := i.(sdk.Dec); !ok { + if _, ok := i.(math.LegacyDec); !ok { return fmt.Errorf("invalid parameter type: %T", i) } return nil @@ -253,7 +253,7 @@ func validateSlashFractionBatch(i interface{}) error { func validateSlashFractionBadEthSignature(i interface{}) error { // TODO: do we want to set some bounds on this value? - if _, ok := i.(sdk.Dec); !ok { + if _, ok := i.(math.LegacyDec); !ok { return fmt.Errorf("invalid parameter type: %T", i) } return nil diff --git a/x/gravity/types/genesis_test.go b/x/gravity/types/genesis_test.go index 13b11ec2..4fc38a88 100644 --- a/x/gravity/types/genesis_test.go +++ b/x/gravity/types/genesis_test.go @@ -3,7 +3,7 @@ package types import ( "testing" - types "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/math" "github.com/stretchr/testify/require" ) @@ -23,8 +23,8 @@ func TestGenesisStateValidate(t *testing.T) { TargetBatchTimeout: 0, AverageBlockTime: 0, AverageEthereumBlockTime: 0, - SlashFractionBatch: types.Dec{}, - SlashFractionBadEthSignature: types.Dec{}, + SlashFractionBatch: math.LegacyDec{}, + SlashFractionBadEthSignature: math.LegacyDec{}, }, GravityNonces: GravityNonces{}, Batches: []OutgoingTxBatch{}, @@ -42,8 +42,8 @@ func TestGenesisStateValidate(t *testing.T) { TargetBatchTimeout: 0, AverageBlockTime: 0, AverageEthereumBlockTime: 0, - SlashFractionBatch: types.Dec{}, - SlashFractionBadEthSignature: types.Dec{}, + SlashFractionBatch: math.LegacyDec{}, + SlashFractionBadEthSignature: math.LegacyDec{}, }, GravityNonces: GravityNonces{}, Batches: []OutgoingTxBatch{}, diff --git a/x/gravity/types/key_test.go b/x/gravity/types/key_test.go index 8344c651..b18b282a 100644 --- a/x/gravity/types/key_test.go +++ b/x/gravity/types/key_test.go @@ -3,7 +3,7 @@ package types import ( "testing" - sdk "github.com/cosmos/cosmos-sdk/types" + "cosmossdk.io/math" "github.com/stretchr/testify/require" ) @@ -64,7 +64,7 @@ func getAllKeys(t *testing.T) [][]byte { // Claim, InvalidationId dummyBytes := []byte("0xc783df8a850f42e7F7e57013759C285caa701eB6") // InternationalERC20Token - dummyErc := InternalERC20Token{Amount: sdk.OneInt(), Contract: dummyEthAddr} + dummyErc := InternalERC20Token{Amount: math.OneInt(), Contract: dummyEthAddr} // Denom dummyChainReferenceID := "test-chain" diff --git a/x/gravity/types/msgs.go b/x/gravity/types/msgs.go index d2a6aaec..aaee1031 100644 --- a/x/gravity/types/msgs.go +++ b/x/gravity/types/msgs.go @@ -4,9 +4,10 @@ import ( "encoding/hex" "fmt" + sdkerrors "cosmossdk.io/errors" "github.com/cometbft/cometbft/crypto/tmhash" sdk "github.com/cosmos/cosmos-sdk/types" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + errorsmod "github.com/cosmos/cosmos-sdk/types/errors" "github.com/palomachain/paloma/util/libmeta" ) @@ -44,7 +45,7 @@ func (msg MsgSendToEth) ValidateBasic() error { } if !msg.Amount.IsValid() || msg.Amount.IsZero() { - return sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "amount") + return sdkerrors.Wrap(errorsmod.ErrInvalidCoins, "amount") } if err := ValidateEthAddress(msg.EthDest); err != nil { diff --git a/x/gravity/types/msgs_test.go b/x/gravity/types/msgs_test.go index 3a60ae33..dd343626 100644 --- a/x/gravity/types/msgs_test.go +++ b/x/gravity/types/msgs_test.go @@ -3,6 +3,7 @@ package types import ( "testing" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" "golang.org/x/exp/slices" @@ -35,7 +36,7 @@ func TestMsgSendToPalomaClaimHash(t *testing.T) { EventNonce: 0, EthBlockHeight: 0, TokenContract: "", - Amount: sdk.Int{}, + Amount: math.Int{}, EthereumSender: "", PalomaReceiver: "", Orchestrator: "", diff --git a/x/gravity/types/test_utils.go b/x/gravity/types/test_utils.go index cb32dcd3..cd853598 100644 --- a/x/gravity/types/test_utils.go +++ b/x/gravity/types/test_utils.go @@ -5,6 +5,7 @@ import ( "math/big" "math/rand" + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -38,13 +39,13 @@ func NonemptyEthAddress() (ret string) { } // Creates a random nonzero sdk.Int test value -func NonzeroSdkInt() (ret sdk.Int) { +func NonzeroSdkInt() (ret math.Int) { amount := big.NewInt(0) for amount.Cmp(big.NewInt(0)) == 0 { amountBz := make([]byte, 32) rand.Read(amountBz) //nolint:gosec amount = big.NewInt(0).SetBytes(amountBz) } - ret = sdk.NewIntFromBigInt(amount) + ret = math.NewIntFromBigInt(amount) return } diff --git a/x/gravity/types/validation.go b/x/gravity/types/validation.go index c9086ed3..002dff48 100644 --- a/x/gravity/types/validation.go +++ b/x/gravity/types/validation.go @@ -4,7 +4,7 @@ import ( "math" "sort" - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" ) ////////////////////////////////////// diff --git a/x/treasury/genesis.go b/x/treasury/genesis.go index 0c3c4c42..7ececfaa 100644 --- a/x/treasury/genesis.go +++ b/x/treasury/genesis.go @@ -1,6 +1,8 @@ package treasury import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/palomachain/paloma/x/treasury/keeper" "github.com/palomachain/paloma/x/treasury/types" @@ -8,26 +10,29 @@ import ( // InitGenesis initializes the capability module's state from a provided genesis // state. -func InitGenesis(ctx sdk.Context, k keeper.Keeper, genState types.GenesisState) { - k.SetParams(ctx, genState.Params) +func InitGenesis(ctx context.Context, k keeper.Keeper, genState types.GenesisState) { + sdkctx := sdk.UnwrapSDKContext(ctx) + k.SetParams(sdkctx, genState.Params) - err := k.SetCommunityFundFee(ctx, "0.01") + err := k.SetCommunityFundFee(sdkctx, "0.01") if err != nil { panic(err) } - err = k.SetSecurityFee(ctx, "0.01") + err = k.SetSecurityFee(sdkctx, "0.01") if err != nil { panic(err) } } // ExportGenesis returns the capability module's exported genesis. -func ExportGenesis(ctx sdk.Context, k keeper.Keeper) *types.GenesisState { +func ExportGenesis(ctx context.Context, k keeper.Keeper) *types.GenesisState { + sdkctx := sdk.UnwrapSDKContext(ctx) + genesis := types.DefaultGenesis() - genesis.Params = k.GetParams(ctx) + genesis.Params = k.GetParams(sdkctx) - fees, err := k.GetFees(ctx) + fees, err := k.GetFees(sdkctx) if err != nil { panic(err) } diff --git a/x/treasury/keeper/grpc_query_fees_test.go b/x/treasury/keeper/grpc_query_fees_test.go index 78c3befe..3443fb70 100644 --- a/x/treasury/keeper/grpc_query_fees_test.go +++ b/x/treasury/keeper/grpc_query_fees_test.go @@ -3,7 +3,7 @@ package keeper import ( "testing" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" keeperutilmocks "github.com/palomachain/paloma/util/keeper/mocks" diff --git a/x/treasury/keeper/keeper.go b/x/treasury/keeper/keeper.go index 7edf6972..efad3887 100644 --- a/x/treasury/keeper/keeper.go +++ b/x/treasury/keeper/keeper.go @@ -1,12 +1,13 @@ package keeper import ( + "context" "errors" "fmt" - "github.com/cometbft/cometbft/libs/log" + cosmosstore "cosmossdk.io/core/store" + "cosmossdk.io/log" "github.com/cosmos/cosmos-sdk/codec" - storetypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" xchain "github.com/palomachain/paloma/internal/x-chain" @@ -18,7 +19,6 @@ const storeKey = "treasury" type Keeper struct { cdc codec.BinaryCodec - memKey storetypes.StoreKey paramstore paramtypes.Subspace bank types.BankKeeper account types.AccountKeeper @@ -30,8 +30,7 @@ type Keeper struct { func NewKeeper( cdc codec.BinaryCodec, - storeKey, - memKey storetypes.StoreKey, + storeKey cosmosstore.KVStoreService, ps paramtypes.Subspace, bank types.BankKeeper, account types.AccountKeeper, @@ -44,7 +43,6 @@ func NewKeeper( return &Keeper{ cdc: cdc, - memKey: memKey, paramstore: ps, bank: bank, account: account, @@ -58,11 +56,12 @@ func NewKeeper( func (k Keeper) ModuleName() string { return types.ModuleName } -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +func (k Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } -func (k Keeper) SetCommunityFundFee(ctx sdk.Context, fee string) error { +func (k Keeper) SetCommunityFundFee(ctx context.Context, fee string) error { fees, err := k.GetFees(ctx) if err != nil { return err @@ -75,7 +74,7 @@ func (k Keeper) SetCommunityFundFee(ctx sdk.Context, fee string) error { return err } -func (k Keeper) SetSecurityFee(ctx sdk.Context, fee string) error { +func (k Keeper) SetSecurityFee(ctx context.Context, fee string) error { fees, err := k.GetFees(ctx) if err != nil { return err @@ -88,7 +87,7 @@ func (k Keeper) SetSecurityFee(ctx sdk.Context, fee string) error { return err } -func (k Keeper) GetFees(ctx sdk.Context) (*types.Fees, error) { +func (k Keeper) GetFees(ctx context.Context) (*types.Fees, error) { res, err := k.KeeperUtil.Load(k.Store.TreasuryStore(ctx), k.cdc, []byte(storeKey)) if errors.Is(err, keeperutil.ErrNotFound) { return &types.Fees{}, nil @@ -99,6 +98,6 @@ func (k Keeper) GetFees(ctx sdk.Context) (*types.Fees, error) { return res, nil } -func (k Keeper) setFees(ctx sdk.Context, fees *types.Fees) error { +func (k Keeper) setFees(ctx context.Context, fees *types.Fees) error { return k.KeeperUtil.Save(k.Store.TreasuryStore(ctx), k.cdc, []byte(storeKey), fees) } diff --git a/x/treasury/keeper/keeper_test.go b/x/treasury/keeper/keeper_test.go index 44cc58c0..850eaa74 100644 --- a/x/treasury/keeper/keeper_test.go +++ b/x/treasury/keeper/keeper_test.go @@ -4,7 +4,7 @@ import ( "errors" "testing" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" keeperutil "github.com/palomachain/paloma/util/keeper" diff --git a/x/treasury/module.go b/x/treasury/module.go index 075b5097..f37499cb 100644 --- a/x/treasury/module.go +++ b/x/treasury/module.go @@ -1,9 +1,11 @@ package treasury import ( + "context" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -19,14 +21,25 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.HasServices = AppModule{} + _ module.HasInvariants = AppModule{} + _ module.HasABCIGenesis = AppModule{} + _ module.HasConsensusVersion = AppModule{} + _ module.HasName = AppModule{} + + _ appmodule.HasEndBlocker = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} + _ appmodule.AppModule = AppModule{} ) // ---------------------------------------------------------------------------- // AppModuleBasic // ---------------------------------------------------------------------------- +func (m AppModule) IsOnePerModuleType() {} +func (m AppModule) IsAppModule() {} + // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { cdc codec.BinaryCodec @@ -153,10 +166,10 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw func (AppModule) ConsensusVersion() uint64 { return 1 } // BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} +func (am AppModule) BeginBlock(_ context.Context) error { return nil } // EndBlock executes all ABCI EndBlock logic respective to the capability module. It // returns no validator updates. -func (am AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - return []abci.ValidatorUpdate{} +func (am AppModule) EndBlock(_ context.Context) error { + return nil } diff --git a/x/treasury/module_simulation.go b/x/treasury/module_simulation.go index 5441995b..b1cce468 100644 --- a/x/treasury/module_simulation.go +++ b/x/treasury/module_simulation.go @@ -2,7 +2,6 @@ package treasury import ( "github.com/cosmos/cosmos-sdk/baseapp" - 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/simulation" @@ -37,7 +36,7 @@ func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedP } // RegisterStoreDecoder registers a decoder -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { diff --git a/x/treasury/types/errors.go b/x/treasury/types/errors.go index e69d2a3c..05e043b5 100644 --- a/x/treasury/types/errors.go +++ b/x/treasury/types/errors.go @@ -3,7 +3,7 @@ package types // DONTCOVER import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" ) // x/treasury module sentinel errors diff --git a/x/treasury/types/expected_keepers.go b/x/treasury/types/expected_keepers.go index 26eeaa17..420f9c60 100644 --- a/x/treasury/types/expected_keepers.go +++ b/x/treasury/types/expected_keepers.go @@ -1,33 +1,34 @@ package types import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" schedulertypes "github.com/palomachain/paloma/x/scheduler/types" ) // AccountKeeper defines the expected account keeper used for simulations (noalias) type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI - NewAccount(ctx sdk.Context, acc types.AccountI) types.AccountI - HasAccount(ctx sdk.Context, addr sdk.AccAddress) bool - SetAccount(ctx sdk.Context, acc types.AccountI) + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI + NewAccount(ctx context.Context, acc sdk.AccountI) sdk.AccountI + HasAccount(ctx context.Context, addr sdk.AccAddress) bool + SetAccount(ctx context.Context, acc sdk.AccountI) // Methods imported from account should be defined here } // BankKeeper defines the expected interface needed to retrieve account balances. type BankKeeper interface { - GetBalance(ctx sdk.Context, addr sdk.AccAddress, denom string) sdk.Coin - HasBalance(ctx sdk.Context, addr sdk.AccAddress, amt sdk.Coin) bool - GetAllBalances(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + GetBalance(ctx context.Context, addr sdk.AccAddress, denom string) sdk.Coin + HasBalance(ctx context.Context, addr sdk.AccAddress, amt sdk.Coin) bool + GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins - SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error - SendCoinsFromAccountToModule(ctx sdk.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error + SendCoinsFromModuleToAccount(ctx context.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error + SendCoinsFromAccountToModule(ctx context.Context, senderAddr sdk.AccAddress, recipientModule string, amt sdk.Coins) error - MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error - BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error + MintCoins(ctx context.Context, moduleName string, amt sdk.Coins) error + BurnCoins(ctx context.Context, moduleName string, amt sdk.Coins) error } type Scheduler interface { - GetJob(ctx sdk.Context, jobID string) (*schedulertypes.Job, error) + GetJob(ctx context.Context, jobID string) (*schedulertypes.Job, error) } diff --git a/x/treasury/types/mocks/TreasuryStore.go b/x/treasury/types/mocks/TreasuryStore.go index db4e0d43..ec4503b5 100644 --- a/x/treasury/types/mocks/TreasuryStore.go +++ b/x/treasury/types/mocks/TreasuryStore.go @@ -1,12 +1,13 @@ -// Code generated by mockery v2.20.0. DO NOT EDIT. +// Code generated by mockery v2.38.0. DO NOT EDIT. package mocks import ( - storetypes "github.com/cosmos/cosmos-sdk/store/types" + context "context" + mock "github.com/stretchr/testify/mock" - types "github.com/cosmos/cosmos-sdk/types" + types "cosmossdk.io/store/types" ) // TreasuryStore is an autogenerated mock type for the TreasuryStore type @@ -15,28 +16,31 @@ type TreasuryStore struct { } // TreasuryStore provides a mock function with given fields: ctx -func (_m *TreasuryStore) TreasuryStore(ctx types.Context) storetypes.KVStore { +func (_m *TreasuryStore) TreasuryStore(ctx context.Context) types.KVStore { ret := _m.Called(ctx) - var r0 storetypes.KVStore - if rf, ok := ret.Get(0).(func(types.Context) storetypes.KVStore); ok { + if len(ret) == 0 { + panic("no return value specified for TreasuryStore") + } + + var r0 types.KVStore + if rf, ok := ret.Get(0).(func(context.Context) types.KVStore); ok { r0 = rf(ctx) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(storetypes.KVStore) + r0 = ret.Get(0).(types.KVStore) } } return r0 } -type mockConstructorTestingTNewTreasuryStore interface { +// NewTreasuryStore creates a new instance of TreasuryStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewTreasuryStore(t interface { mock.TestingT Cleanup(func()) -} - -// NewTreasuryStore creates a new instance of TreasuryStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewTreasuryStore(t mockConstructorTestingTNewTreasuryStore) *TreasuryStore { +}) *TreasuryStore { mock := &TreasuryStore{} mock.Mock.Test(t) diff --git a/x/treasury/types/params.go b/x/treasury/types/params.go index 357196ad..4f3215e3 100644 --- a/x/treasury/types/params.go +++ b/x/treasury/types/params.go @@ -2,7 +2,6 @@ package types import ( paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" - "gopkg.in/yaml.v2" ) var _ paramtypes.ParamSet = (*Params)(nil) @@ -31,9 +30,3 @@ func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { func (p Params) Validate() error { return nil } - -// String implements the Stringer interface. -func (p Params) String() string { - out, _ := yaml.Marshal(p) - return string(out) -} diff --git a/x/treasury/types/params.pb.go b/x/treasury/types/params.pb.go index 79908e28..62345cd1 100644 --- a/x/treasury/types/params.pb.go +++ b/x/treasury/types/params.pb.go @@ -5,7 +5,6 @@ package types import ( fmt "fmt" - _ "github.com/cosmos/gogoproto/gogoproto" proto "github.com/cosmos/gogoproto/proto" io "io" math "math" @@ -27,8 +26,9 @@ const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package type Params struct { } -func (m *Params) Reset() { *m = Params{} } -func (*Params) ProtoMessage() {} +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_beaa29e219eae478, []int{0} } @@ -68,17 +68,16 @@ func init() { } var fileDescriptor_beaa29e219eae478 = []byte{ - // 154 bytes of a gzipped FileDescriptorProto + // 135 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xd2, 0x28, 0x48, 0xcc, 0xc9, 0xcf, 0x4d, 0x4c, 0xce, 0x48, 0xcc, 0xcc, 0xd3, 0x87, 0xb0, 0xf5, 0x4b, 0x8a, 0x52, 0x13, 0x8b, 0x4b, 0x8b, 0x2a, 0xf5, 0x0b, 0x12, 0x8b, 0x12, 0x73, 0x8b, 0xf5, 0x0a, 0x8a, 0xf2, 0x4b, 0xf2, - 0x85, 0xa4, 0x91, 0x54, 0xea, 0x41, 0xd8, 0x7a, 0x30, 0x95, 0x52, 0x22, 0xe9, 0xf9, 0xe9, 0xf9, - 0x60, 0x75, 0xfa, 0x20, 0x16, 0x44, 0x8b, 0x12, 0x1f, 0x17, 0x5b, 0x00, 0xd8, 0x08, 0x2b, 0x96, - 0x19, 0x0b, 0xe4, 0x19, 0x9c, 0x3c, 0x4e, 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, 0x2f, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39, 0x3f, 0x57, 0x1f, 0x8b, 0x8b, 0x2a, - 0x10, 0x6e, 0x2a, 0xa9, 0x2c, 0x48, 0x2d, 0x4e, 0x62, 0x03, 0x5b, 0x60, 0x0c, 0x08, 0x00, 0x00, - 0xff, 0xff, 0xb4, 0x62, 0xcc, 0x5b, 0xbf, 0x00, 0x00, 0x00, + 0x85, 0xa4, 0x91, 0x54, 0xea, 0x41, 0xd8, 0x7a, 0x30, 0x95, 0x4a, 0x1c, 0x5c, 0x6c, 0x01, 0x60, + 0xc5, 0x4e, 0x1e, 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, 0x97, 0x9e, + 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x8f, 0xc5, 0xd6, 0x0a, 0x84, 0xbd, 0x25, + 0x95, 0x05, 0xa9, 0xc5, 0x49, 0x6c, 0x60, 0x7b, 0x8d, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0x38, + 0x9a, 0x75, 0x4c, 0xa3, 0x00, 0x00, 0x00, } func (m *Params) Marshal() (dAtA []byte, err error) { diff --git a/x/treasury/types/store.go b/x/treasury/types/store.go index 2e062fa2..df3a852d 100644 --- a/x/treasury/types/store.go +++ b/x/treasury/types/store.go @@ -1,19 +1,22 @@ package types import ( - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" + "context" + + cosmosstore "cosmossdk.io/core/store" + "cosmossdk.io/store" + storetypes "cosmossdk.io/store/types" + "github.com/cosmos/cosmos-sdk/runtime" ) type TreasuryStore interface { - TreasuryStore(ctx sdk.Context) sdk.KVStore + TreasuryStore(ctx context.Context) storetypes.KVStore } type Store struct { - StoreKey storetypes.StoreKey + StoreKey cosmosstore.KVStoreService } -func (sg Store) TreasuryStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(sg.StoreKey), []byte("treasury")) +func (sg Store) TreasuryStore(ctx context.Context) store.KVStore { + return runtime.KVStoreAdapter(sg.StoreKey.OpenKVStore(ctx)) } diff --git a/x/valset/keeper/grpc_query_get_alive_pigeons.go b/x/valset/keeper/grpc_query_get_alive_pigeons.go index 007df8ae..3903e093 100644 --- a/x/valset/keeper/grpc_query_get_alive_pigeons.go +++ b/x/valset/keeper/grpc_query_get_alive_pigeons.go @@ -2,9 +2,9 @@ package keeper import ( "context" - sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + keeperutil "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/util/slice" "github.com/palomachain/paloma/x/valset/types" "google.golang.org/grpc/codes" @@ -21,10 +21,14 @@ func (k Keeper) GetAlivePigeons(goCtx context.Context, req *types.QueryGetAliveP vals := k.GetUnjailedValidators(ctx) res := slice.Map(vals, func(val stakingtypes.ValidatorI) *types.QueryGetAlivePigeonsResponse_ValidatorAlive { - until, err := k.ValidatorAliveUntil(ctx, val.GetOperator()) + bz, err := keeperutil.ValAddressFromBech32(k.addressCodec, val.GetOperator()) s := &types.QueryGetAlivePigeonsResponse_ValidatorAlive{ - ValAddress: val.GetOperator(), + ValAddress: bz, + } + if err != nil { + s.Error = err.Error() } + until, err := k.ValidatorAliveUntil(ctx, bz) if err != nil { s.Error = err.Error() } else { diff --git a/x/valset/keeper/grpc_query_get_latest_published_snapshot_test.go b/x/valset/keeper/grpc_query_get_latest_published_snapshot_test.go index 3e6a7d13..4b61e1f9 100644 --- a/x/valset/keeper/grpc_query_get_latest_published_snapshot_test.go +++ b/x/valset/keeper/grpc_query_get_latest_published_snapshot_test.go @@ -1,27 +1,26 @@ package keeper import ( + "context" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" keeperutil "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/x/valset/types" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" ) func TestGetLatestPublishedSnapshot(t *testing.T) { testcases := []struct { name string - setup func(sdk.Context, *Keeper, mockedServices) *types.QueryGetLatestPublishedSnapshotResponse + setup func(context.Context, *Keeper, mockedServices) *types.QueryGetLatestPublishedSnapshotResponse request *types.QueryGetLatestPublishedSnapshotRequest expectedError error }{ { name: "returns the latest published snapshot", - setup: func(ctx sdk.Context, k *Keeper, ms mockedServices) *types.QueryGetLatestPublishedSnapshotResponse { - ms.StakingKeeper.On("IterateValidators", mock.Anything, mock.Anything).Return(nil) + setup: func(ctx context.Context, k *Keeper, ms mockedServices) *types.QueryGetLatestPublishedSnapshotResponse { + // ms.StakingKeeper.("IterateValidators", mock.Anything, mock.Anything).Return(nil) snapshot, err := k.createNewSnapshot(ctx) require.NoError(t, err) @@ -47,7 +46,7 @@ func TestGetLatestPublishedSnapshot(t *testing.T) { }, { name: "returns error when no snapshot published", - setup: func(ctx sdk.Context, k *Keeper, ms mockedServices) *types.QueryGetLatestPublishedSnapshotResponse { + setup: func(ctx context.Context, k *Keeper, ms mockedServices) *types.QueryGetLatestPublishedSnapshotResponse { return nil }, request: &types.QueryGetLatestPublishedSnapshotRequest{ diff --git a/x/valset/keeper/grpc_query_get_validator_jail_reason.go b/x/valset/keeper/grpc_query_get_validator_jail_reason.go index c548d3b6..028a6513 100644 --- a/x/valset/keeper/grpc_query_get_validator_jail_reason.go +++ b/x/valset/keeper/grpc_query_get_validator_jail_reason.go @@ -17,7 +17,11 @@ func (k Keeper) GetValidatorJailReason(goCtx context.Context, req *types.QueryGe ctx := sdk.UnwrapSDKContext(goCtx) - if !k.IsJailed(ctx, req.GetValAddress()) { + jailed, err := k.IsJailed(ctx, req.GetValAddress()) + if err != nil { + return nil, err + } + if !jailed { return nil, whoops.String("validator is not jailed") } diff --git a/x/valset/keeper/grpc_query_params_test.go b/x/valset/keeper/grpc_query_params_test.go index 71f5ca34..9e87f4b8 100644 --- a/x/valset/keeper/grpc_query_params_test.go +++ b/x/valset/keeper/grpc_query_params_test.go @@ -11,7 +11,7 @@ import ( func TestParamsQuery(t *testing.T) { keeper, ctx := testkeeper.ValsetKeeper(t) - wctx := sdk.WrapSDKContext(ctx) + wctx := sdk.UnwrapSDKContext(ctx) params := types.DefaultParams() keeper.SetParams(ctx, params) diff --git a/x/valset/keeper/keep_alive.go b/x/valset/keeper/keep_alive.go index a0d47d4e..f3968bba 100644 --- a/x/valset/keeper/keep_alive.go +++ b/x/valset/keeper/keep_alive.go @@ -2,14 +2,19 @@ package keeper import ( "bytes" + "context" "encoding/json" "errors" + keeperutil "github.com/palomachain/paloma/util/keeper" "time" + "cosmossdk.io/store/prefix" + storetypes "cosmossdk.io/store/types" "github.com/VolumeFi/whoops" - "github.com/cosmos/cosmos-sdk/store/prefix" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/util/libvalid" "github.com/palomachain/paloma/util/slice" "github.com/palomachain/paloma/x/valset/types" @@ -31,7 +36,8 @@ type keepAliveData struct { AliveUntilBlockHeight int64 } -func (k Keeper) KeepValidatorAlive(ctx sdk.Context, valAddr sdk.ValAddress, pigeonVersion string) error { +func (k Keeper) KeepValidatorAlive(ctx context.Context, valAddr sdk.ValAddress, pigeonVersion string) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) if err := k.CanAcceptKeepAlive(ctx, valAddr, pigeonVersion); err != nil { return err } @@ -39,8 +45,8 @@ func (k Keeper) KeepValidatorAlive(ctx sdk.Context, valAddr sdk.ValAddress, pige store := k.keepAliveStore(ctx) data := keepAliveData{ ValAddr: valAddr, - ContactedAt: ctx.BlockTime(), - AliveUntilBlockHeight: ctx.BlockHeader().Height + cJailingDefaultKeepAliveBlockHeight, + ContactedAt: sdkCtx.BlockTime(), + AliveUntilBlockHeight: sdkCtx.BlockHeader().Height + cJailingDefaultKeepAliveBlockHeight, } bz, err := json.Marshal(data) if err != nil { @@ -50,16 +56,18 @@ func (k Keeper) KeepValidatorAlive(ctx sdk.Context, valAddr sdk.ValAddress, pige return nil } -func (k Keeper) IsValidatorAlive(ctx sdk.Context, valAddr sdk.ValAddress) (bool, error) { +func (k Keeper) IsValidatorAlive(ctx context.Context, valAddr sdk.ValAddress) (bool, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) aliveUntil, err := k.ValidatorAliveUntil(ctx, valAddr) if err != nil { return false, err } - return ctx.BlockHeight() < aliveUntil, nil + return sdkCtx.BlockHeight() < aliveUntil, nil } -func (k Keeper) ValidatorAliveUntil(ctx sdk.Context, valAddr sdk.ValAddress) (int64, error) { +func (k Keeper) ValidatorAliveUntil(ctx context.Context, valAddr sdk.ValAddress) (int64, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) store := k.keepAliveStore(ctx) if !store.Has(valAddr) { return 0, ErrValidatorNotInKeepAlive.Format(valAddr) @@ -72,15 +80,18 @@ func (k Keeper) ValidatorAliveUntil(ctx sdk.Context, valAddr sdk.ValAddress) (in return 0, err } - if data.AliveUntilBlockHeight-ctx.BlockHeight() <= cJailingImminentThresholdBlockHeight { - k.Logger(ctx).Info("Validator TTL is about to run out. Jailing is imminent.", "validator-address", data.ValAddr) + if data.AliveUntilBlockHeight-sdkCtx.BlockHeight() <= cJailingImminentThresholdBlockHeight { + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("validator-address", data.ValAddr).Info("Validator TTL is about to run out. Jailing is imminent.") } return data.AliveUntilBlockHeight, nil } -func (k Keeper) CanAcceptKeepAlive(ctx sdk.Context, valAddr sdk.ValAddress, pigeonVersion string) error { - stakingVal := k.staking.Validator(ctx, valAddr) +func (k Keeper) CanAcceptKeepAlive(ctx context.Context, valAddr sdk.ValAddress, pigeonVersion string) error { + stakingVal, err := k.staking.Validator(ctx, valAddr) + if err != nil { + return err + } if stakingVal == nil { return ErrValidatorWithAddrNotFound.Format(valAddr.String()) @@ -93,9 +104,11 @@ func (k Keeper) CanAcceptKeepAlive(ctx sdk.Context, valAddr sdk.ValAddress, pige return nil } -func (k Keeper) CanAcceptValidator(ctx sdk.Context, valAddr sdk.ValAddress) error { - stakingVal := k.staking.Validator(ctx, valAddr) - +func (k Keeper) CanAcceptValidator(ctx context.Context, valAddr sdk.ValAddress) error { + stakingVal, err := k.staking.Validator(ctx, valAddr) + if err != nil { + return err + } if stakingVal == nil { return ErrValidatorWithAddrNotFound.Format(valAddr.String()) } @@ -117,7 +130,8 @@ func (k Keeper) CanAcceptValidator(ctx sdk.Context, valAddr sdk.ValAddress) erro // Active validators are stored as one flattened entry to relief pressure on // reads every block. // Call this during the EndBlock logic. -func (k Keeper) UpdateGracePeriod(ctx sdk.Context) { +func (k Keeper) UpdateGracePeriod(ctx context.Context) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) us := k.unjailedSnapshotStore(ctx) gs := k.gracePeriodStore(ctx) @@ -128,28 +142,39 @@ func (k Keeper) UpdateGracePeriod(ctx sdk.Context) { lookup[string(v)] = struct{}{} } - vals := slice.Map(k.GetUnjailedValidators(ctx), func(i stakingtypes.ValidatorI) []byte { - return i.GetOperator() + vals, err := slice.MapErr(k.GetUnjailedValidators(ctx), func(i stakingtypes.ValidatorI) ([]byte, error) { + bz, err := keeperutil.ValAddressFromBech32(k.addressCodec, i.GetOperator()) + if err != nil { + return nil, err + } + return bz, nil }) + if err != nil { + return err + } for _, v := range vals { if _, found := lookup[string(v)]; !found { // Looks like there's a new unjailed validator. Let's give them // some time before considering jailing them again. - gs.Set(v, sdk.Uint64ToBigEndian(uint64(ctx.BlockHeight()))) + gs.Set(v, sdk.Uint64ToBigEndian(uint64(sdkCtx.BlockHeight()))) } } // Record current snapshot of unjailed validators us.Set([]byte(cUnjailedSnapshotStoreKey), bytes.Join(vals, []byte(","))) + return nil } -func (k Keeper) JailInactiveValidators(ctx sdk.Context) error { +func (k Keeper) JailInactiveValidators(ctx context.Context) error { var g whoops.Group for _, val := range k.GetUnjailedValidators(ctx) { if !(val.GetStatus() == stakingtypes.Bonded || val.GetStatus() == stakingtypes.Unbonding) { continue } - valAddr := val.GetOperator() + valAddr, err := keeperutil.ValAddressFromBech32(k.addressCodec, val.GetOperator()) + if err != nil { + return err + } alive, err := k.IsValidatorAlive(ctx, valAddr) switch { case err == nil: @@ -169,7 +194,11 @@ func (k Keeper) JailInactiveValidators(ctx sdk.Context) error { continue } - if !k.IsJailed(ctx, valAddr) { + jailed, err := k.IsJailed(ctx, valAddr) + if err != nil { + return err + } + if !jailed { g.Add( k.Jail(ctx, valAddr, types.JailReasonPigeonInactive), ) @@ -178,12 +207,14 @@ func (k Keeper) JailInactiveValidators(ctx sdk.Context) error { return g.Return() } -func (k Keeper) isValidatorInGracePeriod(ctx sdk.Context, valAddr sdk.ValAddress) bool { +func (k Keeper) isValidatorInGracePeriod(ctx context.Context, valAddr sdk.ValAddress) bool { + sdkCtx := sdk.UnwrapSDKContext(ctx) store := k.gracePeriodStore(ctx) bytes := store.Get(valAddr) - return libvalid.NotNil(bytes) && ctx.BlockHeight()-int64(sdk.BigEndianToUint64(bytes)) <= cJailingGracePeriodBlockHeight + return libvalid.NotNil(bytes) && sdkCtx.BlockHeight()-int64(sdk.BigEndianToUint64(bytes)) <= cJailingGracePeriodBlockHeight } -func (k Keeper) keepAliveStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("keep-alive/")) +func (k Keeper) keepAliveStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + return prefix.NewStore(store, []byte("keep-alive/")) } diff --git a/x/valset/keeper/keep_alive_test.go b/x/valset/keeper/keep_alive_test.go index 0a67c97d..4f9bd6ea 100644 --- a/x/valset/keeper/keep_alive_test.go +++ b/x/valset/keeper/keep_alive_test.go @@ -45,7 +45,7 @@ func TestJailingInactiveValidators(t *testing.T) { k.unjailedSnapshotStore(ctx).Set([]byte(cUnjailedSnapshotStoreKey), bytes.Join([][]byte{a1, a2, a3, a4}, []byte(","))) ms.StakingKeeper.On("IterateValidators", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - callback := args.Get(1).(func(int64, stakingtypes.ValidatorI) bool) + callback := args.Get(1).(func(int64, *mocks.StakingValidatorI) bool) callback(0, v1) callback(0, v2) callback(0, v3) @@ -151,7 +151,7 @@ func TestUpdateGracePeriod(t *testing.T) { } ms.StakingKeeper.On("IterateValidators", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - callback := args.Get(1).(func(int64, stakingtypes.ValidatorI) bool) + callback := args.Get(1).(func(int64, *mocks.StakingValidatorI) bool) callback(0, v1) callback(0, v2) callback(0, v3) diff --git a/x/valset/keeper/keeper.go b/x/valset/keeper/keeper.go index e82d7b88..b73a99d2 100644 --- a/x/valset/keeper/keeper.go +++ b/x/valset/keeper/keeper.go @@ -2,21 +2,26 @@ package keeper import ( "bytes" + "context" + "cosmossdk.io/core/address" "errors" "fmt" "math/big" "sort" + cosmosstore "cosmossdk.io/core/store" + "cosmossdk.io/log" sdkmath "cosmossdk.io/math" + "cosmossdk.io/store/prefix" + storetypes "cosmossdk.io/store/types" "github.com/VolumeFi/whoops" - "github.com/cometbft/cometbft/libs/log" "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/store/prefix" - storetypes "github.com/cosmos/cosmos-sdk/store/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" keeperutil "github.com/palomachain/paloma/util/keeper" + "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/util/slice" "github.com/palomachain/paloma/x/valset/types" ) @@ -33,18 +38,17 @@ type Keeper struct { cdc codec.BinaryCodec ider keeperutil.IDGenerator - memKey storetypes.StoreKey minimumPigeonVersion string paramstore paramtypes.Subspace powerReduction sdkmath.Int staking types.StakingKeeper - storeKey storetypes.StoreKey + storeKey cosmosstore.KVStoreService + addressCodec address.Codec } func NewKeeper( cdc codec.BinaryCodec, - storeKey, - memKey storetypes.StoreKey, + storeKey cosmosstore.KVStoreService, ps paramtypes.Subspace, staking types.StakingKeeper, minimumPigeonVersion string, @@ -58,36 +62,37 @@ func NewKeeper( k := &Keeper{ cdc: cdc, storeKey: storeKey, - memKey: memKey, paramstore: ps, staking: staking, minimumPigeonVersion: minimumPigeonVersion, powerReduction: powerReduction, } - k.ider = keeperutil.NewIDGenerator(keeperutil.StoreGetterFn(func(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("IDs")) + k.ider = keeperutil.NewIDGenerator(keeperutil.StoreGetterFn(func(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + return prefix.NewStore(store, []byte("IDs")) }), nil) return k } -func (k Keeper) Logger(ctx sdk.Context) log.Logger { - return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) +func (k Keeper) Logger(ctx context.Context) log.Logger { + sdkCtx := sdk.UnwrapSDKContext(ctx) + return sdkCtx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName)) } // TODO: not required now -func (k Keeper) PunishValidator(ctx sdk.Context) {} +func (k Keeper) PunishValidator(ctx context.Context) {} // TODO: not required now -func (k Keeper) Heartbeat(ctx sdk.Context) {} +func (k Keeper) Heartbeat(ctx context.Context) {} // addExternalChainInfo adds external chain info, such as this conductor's address on outside chains so that // we can attribute rewards for running the jobs. -func (k Keeper) AddExternalChainInfo(ctx sdk.Context, valAddr sdk.ValAddress, newChainInfo []*types.ExternalChainInfo) error { +func (k Keeper) AddExternalChainInfo(ctx context.Context, valAddr sdk.ValAddress, newChainInfo []*types.ExternalChainInfo) error { return k.SetExternalChainInfoState(ctx, valAddr, newChainInfo) } -func (k Keeper) SetValidatorBalance(ctx sdk.Context, valAddr sdk.ValAddress, chainType string, chainReferenceID string, externalAddress string, balance *big.Int) error { +func (k Keeper) SetValidatorBalance(ctx context.Context, valAddr sdk.ValAddress, chainType string, chainReferenceID string, externalAddress string, balance *big.Int) error { chainInfos, err := k.GetValidatorChainInfos(ctx, valAddr) if err != nil { return err @@ -107,7 +112,7 @@ func (k Keeper) SetValidatorBalance(ctx sdk.Context, valAddr sdk.ValAddress, cha return k.SetExternalChainInfoState(ctx, valAddr, chainInfos) } -func (k Keeper) SetExternalChainInfoState(ctx sdk.Context, valAddr sdk.ValAddress, chainInfos []*types.ExternalChainInfo) error { +func (k Keeper) SetExternalChainInfoState(ctx context.Context, valAddr sdk.ValAddress, chainInfos []*types.ExternalChainInfo) error { if len(chainInfos) > maxNumOfAllowedExternalAccounts { return ErrMaxNumberOfExternalAccounts.Format( len(chainInfos), @@ -175,34 +180,34 @@ func (k Keeper) SetExternalChainInfoState(ctx sdk.Context, valAddr sdk.ValAddres // TriggerSnapshotBuild creates the snapshot of currently active validators that are // active and registered as conductors. -func (k Keeper) TriggerSnapshotBuild(ctx sdk.Context) (*types.Snapshot, error) { +func (k Keeper) TriggerSnapshotBuild(ctx context.Context) (*types.Snapshot, error) { snapshot, err := k.createNewSnapshot(ctx) if err != nil { return nil, err } - k.Logger(ctx).Info("create new snapshot", "snapshot-id", snapshot.GetId()) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("snapshot-id", snapshot.GetId()).Info("create new snapshot") current, err := k.GetCurrentSnapshot(ctx) if err != nil { return nil, err } - k.Logger(ctx).Info("get current triggered snapshot", "id", current.GetId(), "validator-length", len(current.GetValidators())) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("id", current.GetId(), "validator-length", len(current.GetValidators())).Info("get current triggered snapshot") worthy := k.isNewSnapshotWorthy(ctx, current, snapshot) if !worthy { return nil, nil } - k.Logger(ctx).Info("is worthy", "snapshot-id", current.GetId()) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("snapshot-id", current.GetId()).Info("is worthy") err = k.setSnapshotAsCurrent(ctx, snapshot) if err != nil { return nil, err } - k.Logger(ctx).Info("set snapshot as current", "snapshot-id", snapshot.GetId()) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("snapshot-id", snapshot.GetId()).Info("set snapshot as current") // remove jail reasons for all active validators. // given that a validator is in snapshot, they can't be jailed. @@ -217,9 +222,10 @@ func (k Keeper) TriggerSnapshotBuild(ctx sdk.Context) (*types.Snapshot, error) { return snapshot, err } -func (k Keeper) isNewSnapshotWorthy(ctx sdk.Context, currentSnapshot, newSnapshot *types.Snapshot) bool { +func (k Keeper) isNewSnapshotWorthy(ctx context.Context, currentSnapshot, newSnapshot *types.Snapshot) bool { log := func(reason string) { - k.Logger(ctx).Info("new snapshot is worthy", "reason", reason) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("reason", reason).Info("new snapshot is worthy") + } // if there is no current snapshot, that this new one is worthy if currentSnapshot == nil { @@ -335,7 +341,7 @@ func (k Keeper) isNewSnapshotWorthy(ctx sdk.Context, currentSnapshot, newSnapsho return false } -func (k Keeper) GetUnjailedValidators(ctx sdk.Context) []stakingtypes.ValidatorI { +func (k Keeper) GetUnjailedValidators(ctx context.Context) []stakingtypes.ValidatorI { validators := []stakingtypes.ValidatorI{} k.staking.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) bool { if !val.IsJailed() { @@ -348,13 +354,10 @@ func (k Keeper) GetUnjailedValidators(ctx sdk.Context) []stakingtypes.ValidatorI } // ValidatorSupportsAllChains returns true if the validator supports all chains in the keeper -func (k Keeper) ValidatorSupportsAllChains(ctx sdk.Context, validatorAddress sdk.ValAddress) bool { +func (k Keeper) ValidatorSupportsAllChains(ctx context.Context, validatorAddress sdk.ValAddress) bool { valSupportedChains, err := k.GetValidatorChainInfos(ctx, validatorAddress) if err != nil { - k.Logger(ctx).Error("Unable to get supported chains for validator", - "validator-address", - validatorAddress.String(), - ) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("validator-address", validatorAddress.String()).Error("Unable to get supported chains for validator") return false } @@ -365,37 +368,45 @@ func (k Keeper) ValidatorSupportsAllChains(ctx sdk.Context, validatorAddress sdk missingChains, err := k.EvmKeeper.MissingChains(ctx, valSupportedChainReferenceIDs) if err != nil { - k.Logger(ctx).With("error", err).Error("error checking missing chains for validator", - "validator-address", - validatorAddress.String()) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("validator-address", validatorAddress.String()).Error("error checking missing chains for validator") } return len(missingChains) == 0 } // createNewSnapshot builds a current snapshot of validators. -func (k Keeper) createNewSnapshot(ctx sdk.Context) (*types.Snapshot, error) { +func (k Keeper) createNewSnapshot(ctx context.Context) (*types.Snapshot, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) validators := []stakingtypes.ValidatorI{} k.staking.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) bool { - if val.IsBonded() && !val.IsJailed() && k.ValidatorSupportsAllChains(ctx, val.GetOperator()) { + bz, err := keeperutil.ValAddressFromBech32(k.addressCodec, val.GetOperator()) + if err != nil { + panic(err) + } + if val.IsBonded() && !val.IsJailed() && k.ValidatorSupportsAllChains(ctx, bz) { validators = append(validators, val) } return false }) snapshot := &types.Snapshot{ - Height: ctx.BlockHeight(), - CreatedAt: ctx.BlockTime(), - TotalShares: sdk.ZeroInt(), + Height: sdkCtx.BlockHeight(), + CreatedAt: sdkCtx.BlockTime(), + TotalShares: sdkmath.ZeroInt(), } for _, val := range validators { - chainInfo, err := k.GetValidatorChainInfos(ctx, val.GetOperator()) + bz, err := keeperutil.ValAddressFromBech32(k.addressCodec, val.GetOperator()) + if err != nil { + return nil, err + } + chainInfo, err := k.GetValidatorChainInfos(ctx, bz) if err != nil { return nil, err } snapshot.TotalShares = snapshot.TotalShares.Add(val.GetBondedTokens()) + snapshot.Validators = append(snapshot.Validators, types.Validator{ - Address: val.GetOperator(), + Address: bz, ShareCount: val.GetBondedTokens(), State: types.ValidatorState_ACTIVE, ExternalChainInfos: chainInfo, @@ -405,14 +416,15 @@ func (k Keeper) createNewSnapshot(ctx sdk.Context) (*types.Snapshot, error) { return snapshot, nil } -func (k Keeper) setSnapshotAsCurrent(ctx sdk.Context, snapshot *types.Snapshot) error { +func (k Keeper) setSnapshotAsCurrent(ctx context.Context, snapshot *types.Snapshot) error { snapStore := k.snapshotStore(ctx) - newID := k.ider.IncrementNextID(ctx, snapshotIDKey) + sdkCtx := sdk.UnwrapSDKContext(ctx) + newID := k.ider.IncrementNextID(sdkCtx, snapshotIDKey) snapshot.Id = newID return keeperutil.Save(snapStore, k.cdc, keeperutil.Uint64ToByte(newID), snapshot) } -func (k Keeper) SetSnapshotOnChain(ctx sdk.Context, snapshotID uint64, chainReferenceID string) error { +func (k Keeper) SetSnapshotOnChain(ctx context.Context, snapshotID uint64, chainReferenceID string) error { snapStore := k.snapshotStore(ctx) snapshot, err := k.FindSnapshotByID(ctx, snapshotID) if err != nil { @@ -422,8 +434,9 @@ func (k Keeper) SetSnapshotOnChain(ctx sdk.Context, snapshotID uint64, chainRefe return keeperutil.Save(snapStore, k.cdc, keeperutil.Uint64ToByte(snapshot.Id), snapshot) } -func (k Keeper) GetLatestSnapshotOnChain(ctx sdk.Context, chainReferenceID string) (*types.Snapshot, error) { - snapshotId := k.ider.GetLastID(ctx, snapshotIDKey) +func (k Keeper) GetLatestSnapshotOnChain(ctx context.Context, chainReferenceID string) (*types.Snapshot, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) + snapshotId := k.ider.GetLastID(sdkCtx, snapshotIDKey) // Walk backwards from the most recent snapshot until we find one for this chainReferenceID for { @@ -450,23 +463,24 @@ func (k Keeper) GetLatestSnapshotOnChain(ctx sdk.Context, chainReferenceID strin } // GetCurrentSnapshot returns the currently active snapshot. -func (k Keeper) GetCurrentSnapshot(ctx sdk.Context) (*types.Snapshot, error) { +func (k Keeper) GetCurrentSnapshot(ctx context.Context) (*types.Snapshot, error) { + sdkCtx := sdk.UnwrapSDKContext(ctx) snapStore := k.snapshotStore(ctx) - lastID := k.ider.GetLastID(ctx, snapshotIDKey) + lastID := k.ider.GetLastID(sdkCtx, snapshotIDKey) snapshot, err := keeperutil.Load[*types.Snapshot](snapStore, k.cdc, keeperutil.Uint64ToByte(lastID)) - k.Logger(ctx).Debug("get current snapshot", "last-id", lastID, "snapshot-validator-size", len(snapshot.Validators)) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("last-id", lastID, "snapshot-validator-size", len(snapshot.Validators)).Debug("get current snapshot") if errors.Is(err, keeperutil.ErrNotFound) { return nil, nil } return snapshot, err } -func (k Keeper) FindSnapshotByID(ctx sdk.Context, id uint64) (*types.Snapshot, error) { +func (k Keeper) FindSnapshotByID(ctx context.Context, id uint64) (*types.Snapshot, error) { snapStore := k.snapshotStore(ctx) return keeperutil.Load[*types.Snapshot](snapStore, k.cdc, keeperutil.Uint64ToByte(id)) } -func (k Keeper) GetValidatorChainInfos(ctx sdk.Context, valAddr sdk.ValAddress) ([]*types.ExternalChainInfo, error) { +func (k Keeper) GetValidatorChainInfos(ctx context.Context, valAddr sdk.ValAddress) ([]*types.ExternalChainInfo, error) { info, err := keeperutil.Load[*types.ValidatorExternalAccounts]( k.externalChainInfoStore(ctx, valAddr), k.cdc, @@ -482,7 +496,7 @@ func (k Keeper) GetValidatorChainInfos(ctx sdk.Context, valAddr sdk.ValAddress) return info.ExternalChainInfo, nil } -func (k Keeper) GetAllChainInfos(ctx sdk.Context) ([]*types.ValidatorExternalAccounts, error) { +func (k Keeper) GetAllChainInfos(ctx context.Context) ([]*types.ValidatorExternalAccounts, error) { chainInfoStore := k._externalChainInfoStore(ctx) iter := chainInfoStore.Iterator(nil, nil) @@ -500,7 +514,7 @@ func (k Keeper) GetAllChainInfos(ctx sdk.Context) ([]*types.ValidatorExternalAcc } // GetSigningKey returns a signing key used by the conductor to sign arbitrary messages. -func (k Keeper) GetSigningKey(ctx sdk.Context, valAddr sdk.ValAddress, chainType, chainReferenceID, signedByAddress string) ([]byte, error) { +func (k Keeper) GetSigningKey(ctx context.Context, valAddr sdk.ValAddress, chainType, chainReferenceID, signedByAddress string) ([]byte, error) { externalAccounts, err := k.GetValidatorChainInfos(ctx, valAddr) if err != nil { return nil, err @@ -516,14 +530,18 @@ func (k Keeper) GetSigningKey(ctx sdk.Context, valAddr sdk.ValAddress, chainType } // IsJailed returns if the current validator is jailed or not. -func (k Keeper) IsJailed(ctx sdk.Context, val sdk.ValAddress) bool { - return k.staking.Validator(ctx, val).IsJailed() +func (k Keeper) IsJailed(ctx context.Context, val sdk.ValAddress) (bool, error) { + a, err := k.staking.Validator(ctx, val) + if err != nil { + return a.IsJailed(), err + } + return a.IsJailed(), nil } -func (k Keeper) Jail(ctx sdk.Context, valAddr sdk.ValAddress, reason string) error { - val := k.staking.Validator(ctx, valAddr) - if val == nil { - return ErrValidatorWithAddrNotFound.Format(valAddr) +func (k Keeper) Jail(ctx context.Context, valAddr sdk.ValAddress, reason string) error { + val, err := k.staking.Validator(ctx, valAddr) + if err != nil { + return err } if val.IsJailed() { return ErrValidatorAlreadyJailed.Format(valAddr.String()) @@ -576,24 +594,30 @@ func (k Keeper) Jail(ctx sdk.Context, valAddr sdk.ValAddress, reason string) err return err } - k.Logger(ctx).Info("jailing a validator", "val-addr", valAddr, "reason", reason) + liblog.FromSDKLogger(k.Logger(ctx)).WithFields("val-addr", valAddr, "reason", reason).Info("jailing a validator") + k.jailReasonStore(ctx).Set(valAddr, []byte(reason)) return nil } -func (k Keeper) jailReasonStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("jail-reasons")) +func (k Keeper) jailReasonStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + + return prefix.NewStore(store, []byte("jail-reasons")) } -func (k Keeper) gracePeriodStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("grace-period")) +func (k Keeper) gracePeriodStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + + return prefix.NewStore(store, []byte("grace-period")) } -func (k Keeper) unjailedSnapshotStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("unjailed-snapshot")) +func (k Keeper) unjailedSnapshotStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + return prefix.NewStore(store, []byte("unjailed-snapshot")) } -func (k Keeper) externalChainInfoStore(ctx sdk.Context, val sdk.ValAddress) sdk.KVStore { +func (k Keeper) externalChainInfoStore(ctx context.Context, val sdk.ValAddress) storetypes.KVStore { return prefix.NewStore( k._externalChainInfoStore(ctx), []byte( @@ -602,20 +626,19 @@ func (k Keeper) externalChainInfoStore(ctx sdk.Context, val sdk.ValAddress) sdk. ) } -func (k Keeper) _externalChainInfoStore(ctx sdk.Context) sdk.KVStore { - return prefix.NewStore( - ctx.KVStore(k.storeKey), - []byte("external-chain-info"), - ) +func (k Keeper) _externalChainInfoStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + return prefix.NewStore(store, []byte("external-chain-info")) } -func (k Keeper) snapshotStore(ctx sdk.Context) sdk.KVStore { - k.Logger(ctx).Debug("snapshot store", "store-key-name", k.storeKey.Name(), "store-key-string", k.storeKey.String()) - return prefix.NewStore(ctx.KVStore(k.storeKey), []byte("snapshot")) +func (k Keeper) snapshotStore(ctx context.Context) storetypes.KVStore { + store := runtime.KVStoreAdapter(k.storeKey.OpenKVStore(ctx)) + // k.Logger(ctx).Debug("snapshot store", "store-key-name", k.memKey.Name(), "store-key-string", k.storeKey) //TODO + return prefix.NewStore(store, []byte("snapshot")) } // SaveModifiedSnapshot is needed for integration tests -func (k Keeper) SaveModifiedSnapshot(ctx sdk.Context, snapshot *types.Snapshot) error { +func (k Keeper) SaveModifiedSnapshot(ctx context.Context, snapshot *types.Snapshot) error { snapStore := k.snapshotStore(ctx) return keeperutil.Save(snapStore, k.cdc, keeperutil.Uint64ToByte(snapshot.GetId()), snapshot) } diff --git a/x/valset/keeper/keeper_integration_test.go b/x/valset/keeper/keeper_integration_test.go index 7fa85d7a..31027b73 100644 --- a/x/valset/keeper/keeper_integration_test.go +++ b/x/valset/keeper/keeper_integration_test.go @@ -3,7 +3,6 @@ package keeper_test import ( "testing" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -23,15 +22,13 @@ var _ = Describe("jaling validators", func() { BeforeEach(func() { a = app.NewTestApp(GinkgoT(), false) - ctx = a.NewContext(false, tmproto.Header{ - Height: 5, - }) + ctx = a.NewContext(false) }) Context("with a non existing validator", func() { It("returns an error", func() { validators := testutil.GenValidators(1, 100) - err := a.ValsetKeeper.Jail(ctx, validators[0].GetOperator(), "i am bored") + err := a.ValsetKeeper.Jail(ctx, sdk.ValAddress(validators[0].GetOperator()), "i am bored") Expect(err).To(MatchError(keeper.ErrValidatorWithAddrNotFound)) }) }) @@ -41,9 +38,12 @@ var _ = Describe("jaling validators", func() { BeforeEach(func() { By("query existing validator") - vals := a.StakingKeeper.GetAllValidators(ctx) + vals, err := a.StakingKeeper.GetAllValidators(ctx) + if err != nil { + panic(err) + } Expect(len(vals)).To(Equal(1)) - val = vals[0].GetOperator() + val = sdk.ValAddress(vals[0].GetOperator()) }) It("returns an error that it cannot jail the validator", func() { @@ -62,13 +62,13 @@ var _ = Describe("jaling validators", func() { a.StakingKeeper.SetValidator(ctx, v) a.StakingKeeper.SetValidatorByConsAddr(ctx, v) } - val = validators[0].GetOperator() + val = sdk.ValAddress(validators[0].GetOperator()) }) It("jailes the given validator", func() { err := a.ValsetKeeper.Jail(ctx, val, "i am bored") Expect(err).To(BeNil()) - isJailed := a.ValsetKeeper.IsJailed(ctx, val) + isJailed, err := a.ValsetKeeper.IsJailed(ctx, val) Expect(isJailed).To(BeTrue()) }) When("jailing panics", func() { @@ -77,7 +77,7 @@ var _ = Describe("jaling validators", func() { for _, v := range validators { a.StakingKeeper.SetValidator(ctx, v) } - val = validators[0].GetOperator() + val = sdk.ValAddress(validators[0].GetOperator()) }) It("returns the error if it's of type error or string", func() { err := a.ValsetKeeper.Jail(ctx, val, "i am bored") @@ -102,7 +102,7 @@ var _ = Describe("jaling validators", func() { validators := testutil.GenValidators(1, 100) a.StakingKeeper.SetValidator(ctx, validators[0]) a.StakingKeeper.SetValidatorByConsAddr(ctx, validators[0]) - val = validators[0].GetOperator() + val = sdk.ValAddress(validators[0].GetOperator()) }) It("returns an error", func() { err := a.ValsetKeeper.Jail(ctx, val, "i am bored") diff --git a/x/valset/keeper/keeper_test.go b/x/valset/keeper/keeper_test.go index 03b6edbd..6621e354 100644 --- a/x/valset/keeper/keeper_test.go +++ b/x/valset/keeper/keeper_test.go @@ -3,10 +3,10 @@ package keeper import ( "testing" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + sdkmath "cosmossdk.io/math" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/palomachain/paloma/x/valset/types" "github.com/palomachain/paloma/x/valset/types/mocks" "github.com/stretchr/testify/mock" @@ -160,8 +160,8 @@ func TestCreatingSnapshots(t *testing.T) { vali1.On("IsJailed").Return(false) vali2.On("IsJailed").Return(false) - vali1.On("GetBondedTokens").Return(sdk.NewInt(888)) - vali2.On("GetBondedTokens").Return(sdk.NewInt(222)) + vali1.On("GetBondedTokens").Return(sdkmath.NewInt(888)) + vali2.On("GetBondedTokens").Return(sdkmath.NewInt(222)) vali1.On("IsBonded").Return(true) vali2.On("IsBonded").Return(true) @@ -172,7 +172,7 @@ func TestCreatingSnapshots(t *testing.T) { ms.StakingKeeper.On("Validator", ctx, val2).Return(vali2) ms.StakingKeeper.On("IterateValidators", mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - type fnc = func(int64, stakingtypes.ValidatorI) bool + type fnc = func(int64, *mocks.StakingValidatorI) bool f := args.Get(1).(fnc) f(0, vali1) f(1, vali2) @@ -300,17 +300,17 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: true, name: "two snapshots have same validators but different power orders", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(20)}, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(20)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(80)}, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(20)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(20)}, }, }, }, @@ -318,17 +318,17 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: true, name: "two snapshots have same validators and same relative power orders, but differ in their absolute power more than 1 percent", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(20)}, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(20)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(30)}, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(30)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, }, @@ -336,29 +336,29 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: true, name: "two snapshots are same, but they have removed one of their accounts", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {}, {}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, }, @@ -366,29 +366,29 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: true, name: "two snapshots are same, but they have different external chain infos", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc"}, {Address: "def"}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc"}, {Address: "123"}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, }, @@ -396,29 +396,29 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: false, name: "two snapshots have same validators and same relative power orders", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc"}, {Address: "def"}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(1000), + TotalShares: sdkmath.NewInt(1000), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(200), + ShareCount: sdkmath.NewInt(200), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc"}, {Address: "def"}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(800)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(800)}, }, }, }, @@ -426,29 +426,29 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: false, name: "two snapshots have same validators and same traits", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc", Traits: []string{"abc"}}, {Address: "def", Traits: []string{"abc"}}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(1000), + TotalShares: sdkmath.NewInt(1000), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(200), + ShareCount: sdkmath.NewInt(200), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc", Traits: []string{"abc"}}, {Address: "def", Traits: []string{"abc"}}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(800)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(800)}, }, }, }, @@ -456,29 +456,29 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: true, name: "two snapshots have same validators and different traits", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(20), + ShareCount: sdkmath.NewInt(20), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc", Traits: []string{"abc"}}, {Address: "def", Traits: []string{"abc"}}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(80)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(80)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(1000), + TotalShares: sdkmath.NewInt(1000), Validators: []types.Validator{ { Address: sdk.ValAddress("123"), - ShareCount: sdk.NewInt(200), + ShareCount: sdkmath.NewInt(200), ExternalChainInfos: []*types.ExternalChainInfo{ {Address: "abc", Traits: []string{"abc"}}, {Address: "def", Traits: []string{"def"}}, }, }, - {Address: sdk.ValAddress("456"), ShareCount: sdk.NewInt(800)}, + {Address: sdk.ValAddress("456"), ShareCount: sdkmath.NewInt(800)}, }, }, }, @@ -486,15 +486,15 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: false, name: "if the powers are still the same then it's not worthy", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(20)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(20)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(100), + TotalShares: sdkmath.NewInt(100), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(20)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(20)}, }, }, }, @@ -502,15 +502,15 @@ func TestIsNewSnapshotWorthy(t *testing.T) { expRes: false, name: "if the powers have change for less than 1%, then it's not worthy", curr: &types.Snapshot{ - TotalShares: sdk.NewInt(1000), + TotalShares: sdkmath.NewInt(1000), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(20)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(20)}, }, }, neww: &types.Snapshot{ - TotalShares: sdk.NewInt(1000), + TotalShares: sdkmath.NewInt(1000), Validators: []types.Validator{ - {Address: sdk.ValAddress("123"), ShareCount: sdk.NewInt(21)}, + {Address: sdk.ValAddress("123"), ShareCount: sdkmath.NewInt(21)}, }, }, }, diff --git a/x/valset/keeper/setup_test.go b/x/valset/keeper/setup_test.go index 4057cbe1..3324788b 100644 --- a/x/valset/keeper/setup_test.go +++ b/x/valset/keeper/setup_test.go @@ -1,16 +1,17 @@ package keeper import ( - "os" "testing" - tmdb "github.com/cometbft/cometbft-db" - "github.com/cometbft/cometbft/libs/log" + "cosmossdk.io/log" + "cosmossdk.io/store" + "cosmossdk.io/store/metrics" + storetypes "cosmossdk.io/store/types" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmdb "github.com/cosmos/cosmos-db" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - "github.com/cosmos/cosmos-sdk/store" - storetypes "github.com/cosmos/cosmos-sdk/store/types" + "github.com/cosmos/cosmos-sdk/runtime" sdk "github.com/cosmos/cosmos-sdk/types" typesparams "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/palomachain/paloma/x/valset/types" @@ -24,11 +25,13 @@ type mockedServices struct { } func newValsetKeeper(t testing.TB) (*Keeper, mockedServices, sdk.Context) { - storeKey := sdk.NewKVStoreKey(types.StoreKey) + storeKey := storetypes.NewKVStoreKey(types.StoreKey) + + storeKeyService := runtime.NewKVStoreService(storeKey) memStoreKey := storetypes.NewMemoryStoreKey(types.MemStoreKey) db := tmdb.NewMemDB() - stateStore := store.NewCommitMultiStore(db) + stateStore := store.NewCommitMultiStore(db, log.NewNopLogger(), metrics.NewNoOpMetrics()) stateStore.MountStoreWithDB(storeKey, storetypes.StoreTypeIAVL, db) stateStore.MountStoreWithDB(memStoreKey, storetypes.StoreTypeMemory, nil) require.NoError(t, stateStore.LoadLatestVersion()) @@ -46,13 +49,12 @@ func newValsetKeeper(t testing.TB) (*Keeper, mockedServices, sdk.Context) { ) ms := mockedServices{ - StakingKeeper: mocks.NewStakingKeeper(t), - EvmKeeper: mocks.NewEvmKeeper(t), + StakingKeeper: &mocks.StakingKeeper{}, + EvmKeeper: &mocks.EvmKeeper{}, } k := NewKeeper( appCodec, - storeKey, - memStoreKey, + storeKeyService, paramsSubspace, ms.StakingKeeper, "v1.4.0", @@ -62,9 +64,9 @@ func newValsetKeeper(t testing.TB) (*Keeper, mockedServices, sdk.Context) { k.EvmKeeper = ms.EvmKeeper ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, nil) - ctx = ctx.WithMultiStore(stateStore).WithGasMeter(sdk.NewInfiniteGasMeter()) + ctx = ctx.WithMultiStore(stateStore).WithGasMeter(storetypes.NewInfiniteGasMeter()) - ctx = ctx.WithLogger(log.NewTMJSONLogger(os.Stdout)) + ctx = ctx.WithLogger(log.NewNopLogger()) // Initialize params k.SetParams(ctx, types.DefaultParams()) diff --git a/x/valset/module.go b/x/valset/module.go index ae431778..d5a3206c 100644 --- a/x/valset/module.go +++ b/x/valset/module.go @@ -1,9 +1,11 @@ package valset import ( + "context" "encoding/json" "fmt" + "cosmossdk.io/core/appmodule" abci "github.com/cometbft/cometbft/abci/types" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" @@ -19,14 +21,25 @@ import ( ) var ( - _ module.AppModule = AppModule{} - _ module.AppModuleBasic = AppModuleBasic{} + _ module.AppModuleBasic = AppModuleBasic{} + _ module.HasServices = AppModule{} + _ module.HasInvariants = AppModule{} + _ module.HasABCIGenesis = AppModule{} + _ module.HasConsensusVersion = AppModule{} + _ module.HasName = AppModule{} + + _ appmodule.HasEndBlocker = AppModule{} + _ appmodule.HasBeginBlocker = AppModule{} + _ appmodule.AppModule = AppModule{} ) // ---------------------------------------------------------------------------- // AppModuleBasic // ---------------------------------------------------------------------------- +func (m AppModule) IsOnePerModuleType() {} +func (m AppModule) IsAppModule() {} + // AppModuleBasic implements the AppModuleBasic interface for the capability module. type AppModuleBasic struct { cdc codec.BinaryCodec @@ -153,23 +166,24 @@ func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONCodec) json.Raw func (AppModule) ConsensusVersion() uint64 { return 1 } // BeginBlock executes all ABCI BeginBlock logic respective to the capability module. -func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} +func (am AppModule) BeginBlock(context.Context) error { return nil } // EndBlock executes all ABCI EndBlock logic respective to the capability module. It // returns no validator updates. -func (am AppModule) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { - if ctx.BlockHeight()%50 == 0 || ctx.BlockHeight() == 1 { - if _, err := am.keeper.TriggerSnapshotBuild(ctx); err != nil { - am.keeper.Logger(ctx).Error("error triggering snapshot build", "error", err) +func (am AppModule) EndBlock(ctx context.Context) error { + sdkCtx := sdk.UnwrapSDKContext(ctx) + if sdkCtx.BlockHeight()%50 == 0 || sdkCtx.BlockHeight() == 1 { + if _, err := am.keeper.TriggerSnapshotBuild(sdkCtx); err != nil { + am.keeper.Logger(sdkCtx).Error("error triggering snapshot build", "error", err) } } - am.keeper.UpdateGracePeriod(ctx) + am.keeper.UpdateGracePeriod(sdkCtx) - if ctx.BlockHeight() > 50 && ctx.BlockHeight()%10 == 0 { - if err := am.keeper.JailInactiveValidators(ctx); err != nil { - am.keeper.Logger(ctx).Error("error while jailing inactive validators", "error", err) + if sdkCtx.BlockHeight() > 50 && sdkCtx.BlockHeight()%10 == 0 { + if err := am.keeper.JailInactiveValidators(sdkCtx); err != nil { + am.keeper.Logger(sdkCtx).Error("error while jailing inactive validators", "error", err) } } - return []abci.ValidatorUpdate{} + return nil } diff --git a/x/valset/module_simulation.go b/x/valset/module_simulation.go index b5f4988f..90080e0b 100644 --- a/x/valset/module_simulation.go +++ b/x/valset/module_simulation.go @@ -4,7 +4,7 @@ import ( "math/rand" "github.com/cosmos/cosmos-sdk/baseapp" - 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/simulation" @@ -43,14 +43,14 @@ func (AppModule) ProposalContents(_ module.SimulationState) []simtypes.WeightedP } // RegisterStoreDecoder registers a decoder -func (am AppModule) RegisterStoreDecoder(_ sdk.StoreDecoderRegistry) {} +func (am AppModule) RegisterStoreDecoder(_ simtypes.StoreDecoderRegistry) {} // WeightedOperations returns the all the gov module operations with their respective weights. func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { operations := make([]simtypes.WeightedOperation, 0) var weightMsgAddExternalChainInfoForValidator int - simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgAddExternalChainInfoForValidator, &weightMsgAddExternalChainInfoForValidator, nil, + simState.AppParams.GetOrGenerate(opWeightMsgAddExternalChainInfoForValidator, &weightMsgAddExternalChainInfoForValidator, simState.Rand, func(_ *rand.Rand) { weightMsgAddExternalChainInfoForValidator = defaultWeightMsgAddExternalChainInfoForValidator }, diff --git a/x/valset/types/errors.go b/x/valset/types/errors.go index a5c23506..2da433cb 100644 --- a/x/valset/types/errors.go +++ b/x/valset/types/errors.go @@ -3,7 +3,7 @@ package types // DONTCOVER import ( - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + sdkerrors "cosmossdk.io/errors" ) // x/valset module sentinel errors diff --git a/x/valset/types/expected_keepers.go b/x/valset/types/expected_keepers.go index 619bdf3c..c7101b2a 100644 --- a/x/valset/types/expected_keepers.go +++ b/x/valset/types/expected_keepers.go @@ -1,35 +1,38 @@ package types import ( + "context" + sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) // AccountKeeper defines the expected account keeper used for simulations (noalias) + type AccountKeeper interface { - GetAccount(ctx sdk.Context, addr sdk.AccAddress) types.AccountI + GetAccount(ctx context.Context, addr sdk.AccAddress) sdk.AccountI // Methods imported from account should be defined here } // BankKeeper defines the expected interface needed to retrieve account balances. + type BankKeeper interface { - SpendableCoins(ctx sdk.Context, addr sdk.AccAddress) sdk.Coins + SpendableCoins(ctx context.Context, addr sdk.AccAddress) sdk.Coins // Methods imported from bank should be defined here } //go:generate mockery --name=StakingKeeper //go:generate mockery --srcpkg=github.com/cosmos/cosmos-sdk/x/staking/types --name=ValidatorI --structname=StakingValidatorI type StakingKeeper interface { - Validator(ctx sdk.Context, addr sdk.ValAddress) stakingtypes.ValidatorI - IterateValidators(ctx sdk.Context, fn func(index int64, validator stakingtypes.ValidatorI) (stop bool)) - Jail(ctx sdk.Context, consAddr sdk.ConsAddress) + Validator(ctx context.Context, addr sdk.ValAddress) (stakingtypes.ValidatorI, error) + IterateValidators(ctx context.Context, fn func(index int64, validator stakingtypes.ValidatorI) bool) error + Jail(ctx context.Context, consAddr sdk.ConsAddress) error } type OnSnapshotBuiltListener interface { - OnSnapshotBuilt(sdk.Context, *Snapshot) + OnSnapshotBuilt(context.Context, *Snapshot) } type EvmKeeper interface { - MissingChains(ctx sdk.Context, chainReferenceIDs []string) ([]string, error) + MissingChains(ctx context.Context, chainReferenceIDs []string) ([]string, error) } diff --git a/x/valset/types/mocks/EvmKeeper.go b/x/valset/types/mocks/EvmKeeper.go index 2190546a..98eefd71 100644 --- a/x/valset/types/mocks/EvmKeeper.go +++ b/x/valset/types/mocks/EvmKeeper.go @@ -1,9 +1,10 @@ -// Code generated by mockery v2.20.0. DO NOT EDIT. +// Code generated by mockery v2.38.0. DO NOT EDIT. package mocks import ( - types "github.com/cosmos/cosmos-sdk/types" + context "context" + mock "github.com/stretchr/testify/mock" ) @@ -13,15 +14,19 @@ type EvmKeeper struct { } // MissingChains provides a mock function with given fields: ctx, chainReferenceIDs -func (_m *EvmKeeper) MissingChains(ctx types.Context, chainReferenceIDs []string) ([]string, error) { +func (_m *EvmKeeper) MissingChains(ctx context.Context, chainReferenceIDs []string) ([]string, error) { ret := _m.Called(ctx, chainReferenceIDs) + if len(ret) == 0 { + panic("no return value specified for MissingChains") + } + var r0 []string var r1 error - if rf, ok := ret.Get(0).(func(types.Context, []string) ([]string, error)); ok { + if rf, ok := ret.Get(0).(func(context.Context, []string) ([]string, error)); ok { return rf(ctx, chainReferenceIDs) } - if rf, ok := ret.Get(0).(func(types.Context, []string) []string); ok { + if rf, ok := ret.Get(0).(func(context.Context, []string) []string); ok { r0 = rf(ctx, chainReferenceIDs) } else { if ret.Get(0) != nil { @@ -29,7 +34,7 @@ func (_m *EvmKeeper) MissingChains(ctx types.Context, chainReferenceIDs []string } } - if rf, ok := ret.Get(1).(func(types.Context, []string) error); ok { + if rf, ok := ret.Get(1).(func(context.Context, []string) error); ok { r1 = rf(ctx, chainReferenceIDs) } else { r1 = ret.Error(1) @@ -38,13 +43,12 @@ func (_m *EvmKeeper) MissingChains(ctx types.Context, chainReferenceIDs []string return r0, r1 } -type mockConstructorTestingTNewEvmKeeper interface { +// NewEvmKeeper creates a new instance of EvmKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewEvmKeeper(t interface { mock.TestingT Cleanup(func()) -} - -// NewEvmKeeper creates a new instance of EvmKeeper. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -func NewEvmKeeper(t mockConstructorTestingTNewEvmKeeper) *EvmKeeper { +}) *EvmKeeper { mock := &EvmKeeper{} mock.Mock.Test(t) diff --git a/x/valset/types/mocks/StakingKeeper.go b/x/valset/types/mocks/StakingKeeper.go index 01dc6ffc..23c07504 100644 --- a/x/valset/types/mocks/StakingKeeper.go +++ b/x/valset/types/mocks/StakingKeeper.go @@ -1,11 +1,17 @@ -// Code generated by mockery v2.35.3. DO NOT EDIT. +// Code generated by mockery v2.38.0. DO NOT EDIT. package mocks import ( - types "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + context "context" + + address "cosmossdk.io/core/address" + + cosmos_sdktypes "github.com/cosmos/cosmos-sdk/types" + mock "github.com/stretchr/testify/mock" + + types "github.com/cosmos/cosmos-sdk/x/staking/types" ) // StakingKeeper is an autogenerated mock type for the StakingKeeper type @@ -14,25 +20,85 @@ type StakingKeeper struct { } // IterateValidators provides a mock function with given fields: ctx, fn -func (_m *StakingKeeper) IterateValidators(ctx types.Context, fn func(int64, stakingtypes.ValidatorI) bool) { - _m.Called(ctx, fn) +func (_m *StakingKeeper) IterateValidators(ctx context.Context, fn func(int64, types.ValidatorI) bool) error { + ret := _m.Called(ctx, fn) + + if len(ret) == 0 { + panic("no return value specified for IterateValidators") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, func(int64, types.ValidatorI) bool) error); ok { + r0 = rf(ctx, fn) + } else { + r0 = ret.Error(0) + } + + return r0 } // Jail provides a mock function with given fields: ctx, consAddr -func (_m *StakingKeeper) Jail(ctx types.Context, consAddr types.ConsAddress) { - _m.Called(ctx, consAddr) +func (_m *StakingKeeper) Jail(ctx context.Context, consAddr cosmos_sdktypes.ConsAddress) error { + ret := _m.Called(ctx, consAddr) + + if len(ret) == 0 { + panic("no return value specified for Jail") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, cosmos_sdktypes.ConsAddress) error); ok { + r0 = rf(ctx, consAddr) + } else { + r0 = ret.Error(0) + } + + return r0 } // Validator provides a mock function with given fields: ctx, addr -func (_m *StakingKeeper) Validator(ctx types.Context, addr types.ValAddress) stakingtypes.ValidatorI { +func (_m *StakingKeeper) Validator(ctx context.Context, addr cosmos_sdktypes.ValAddress) (types.ValidatorI, error) { ret := _m.Called(ctx, addr) - var r0 stakingtypes.ValidatorI - if rf, ok := ret.Get(0).(func(types.Context, types.ValAddress) stakingtypes.ValidatorI); ok { + if len(ret) == 0 { + panic("no return value specified for Validator") + } + + var r0 types.ValidatorI + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, cosmos_sdktypes.ValAddress) (types.ValidatorI, error)); ok { + return rf(ctx, addr) + } + if rf, ok := ret.Get(0).(func(context.Context, cosmos_sdktypes.ValAddress) types.ValidatorI); ok { r0 = rf(ctx, addr) } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(stakingtypes.ValidatorI) + r0 = ret.Get(0).(types.ValidatorI) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, cosmos_sdktypes.ValAddress) error); ok { + r1 = rf(ctx, addr) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// ValidatorAddressCodec provides a mock function with given fields: +func (_m *StakingKeeper) ValidatorAddressCodec() address.Codec { + ret := _m.Called() + + if len(ret) == 0 { + panic("no return value specified for ValidatorAddressCodec") + } + + var r0 address.Codec + if rf, ok := ret.Get(0).(func() address.Codec); ok { + r0 = rf() + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(address.Codec) } } @@ -44,8 +110,7 @@ func (_m *StakingKeeper) Validator(ctx types.Context, addr types.ValAddress) sta func NewStakingKeeper(t interface { mock.TestingT Cleanup(func()) -}, -) *StakingKeeper { +}) *StakingKeeper { mock := &StakingKeeper{} mock.Mock.Test(t) diff --git a/x/valset/types/mocks/ValidatorI.go b/x/valset/types/mocks/ValidatorI.go index 9abbc800..d1436333 100644 --- a/x/valset/types/mocks/ValidatorI.go +++ b/x/valset/types/mocks/ValidatorI.go @@ -1,14 +1,16 @@ -// Code generated by mockery v2.35.3. DO NOT EDIT. +// Code generated by mockery v2.38.0. DO NOT EDIT. package mocks import ( math "cosmossdk.io/math" crypto "github.com/cometbft/cometbft/proto/tendermint/crypto" - types "github.com/cosmos/cosmos-sdk/crypto/types" - cosmos_sdktypes "github.com/cosmos/cosmos-sdk/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + mock "github.com/stretchr/testify/mock" + + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + types "github.com/cosmos/cosmos-sdk/crypto/types" ) // StakingValidatorI is an autogenerated mock type for the ValidatorI type @@ -20,6 +22,10 @@ type StakingValidatorI struct { func (_m *StakingValidatorI) ConsPubKey() (types.PubKey, error) { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for ConsPubKey") + } + var r0 types.PubKey var r1 error if rf, ok := ret.Get(0).(func() (types.PubKey, error)); ok { @@ -46,6 +52,10 @@ func (_m *StakingValidatorI) ConsPubKey() (types.PubKey, error) { func (_m *StakingValidatorI) GetBondedTokens() math.Int { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetBondedTokens") + } + var r0 math.Int if rf, ok := ret.Get(0).(func() math.Int); ok { r0 = rf() @@ -60,6 +70,10 @@ func (_m *StakingValidatorI) GetBondedTokens() math.Int { func (_m *StakingValidatorI) GetCommission() math.LegacyDec { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetCommission") + } + var r0 math.LegacyDec if rf, ok := ret.Get(0).(func() math.LegacyDec); ok { r0 = rf() @@ -71,19 +85,23 @@ func (_m *StakingValidatorI) GetCommission() math.LegacyDec { } // GetConsAddr provides a mock function with given fields: -func (_m *StakingValidatorI) GetConsAddr() (cosmos_sdktypes.ConsAddress, error) { +func (_m *StakingValidatorI) GetConsAddr() ([]byte, error) { ret := _m.Called() - var r0 cosmos_sdktypes.ConsAddress + if len(ret) == 0 { + panic("no return value specified for GetConsAddr") + } + + var r0 []byte var r1 error - if rf, ok := ret.Get(0).(func() (cosmos_sdktypes.ConsAddress, error)); ok { + if rf, ok := ret.Get(0).(func() ([]byte, error)); ok { return rf() } - if rf, ok := ret.Get(0).(func() cosmos_sdktypes.ConsAddress); ok { + if rf, ok := ret.Get(0).(func() []byte); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(cosmos_sdktypes.ConsAddress) + r0 = ret.Get(0).([]byte) } } @@ -100,6 +118,10 @@ func (_m *StakingValidatorI) GetConsAddr() (cosmos_sdktypes.ConsAddress, error) func (_m *StakingValidatorI) GetConsensusPower(_a0 math.Int) int64 { ret := _m.Called(_a0) + if len(ret) == 0 { + panic("no return value specified for GetConsensusPower") + } + var r0 int64 if rf, ok := ret.Get(0).(func(math.Int) int64); ok { r0 = rf(_a0) @@ -114,6 +136,10 @@ func (_m *StakingValidatorI) GetConsensusPower(_a0 math.Int) int64 { func (_m *StakingValidatorI) GetDelegatorShares() math.LegacyDec { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetDelegatorShares") + } + var r0 math.LegacyDec if rf, ok := ret.Get(0).(func() math.LegacyDec); ok { r0 = rf() @@ -128,6 +154,10 @@ func (_m *StakingValidatorI) GetDelegatorShares() math.LegacyDec { func (_m *StakingValidatorI) GetMinSelfDelegation() math.Int { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetMinSelfDelegation") + } + var r0 math.Int if rf, ok := ret.Get(0).(func() math.Int); ok { r0 = rf() @@ -142,6 +172,10 @@ func (_m *StakingValidatorI) GetMinSelfDelegation() math.Int { func (_m *StakingValidatorI) GetMoniker() string { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetMoniker") + } + var r0 string if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() @@ -153,16 +187,18 @@ func (_m *StakingValidatorI) GetMoniker() string { } // GetOperator provides a mock function with given fields: -func (_m *StakingValidatorI) GetOperator() cosmos_sdktypes.ValAddress { +func (_m *StakingValidatorI) GetOperator() string { ret := _m.Called() - var r0 cosmos_sdktypes.ValAddress - if rf, ok := ret.Get(0).(func() cosmos_sdktypes.ValAddress); ok { + if len(ret) == 0 { + panic("no return value specified for GetOperator") + } + + var r0 string + if rf, ok := ret.Get(0).(func() string); ok { r0 = rf() } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(cosmos_sdktypes.ValAddress) - } + r0 = ret.Get(0).(string) } return r0 @@ -172,6 +208,10 @@ func (_m *StakingValidatorI) GetOperator() cosmos_sdktypes.ValAddress { func (_m *StakingValidatorI) GetStatus() stakingtypes.BondStatus { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetStatus") + } + var r0 stakingtypes.BondStatus if rf, ok := ret.Get(0).(func() stakingtypes.BondStatus); ok { r0 = rf() @@ -186,6 +226,10 @@ func (_m *StakingValidatorI) GetStatus() stakingtypes.BondStatus { func (_m *StakingValidatorI) GetTokens() math.Int { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for GetTokens") + } + var r0 math.Int if rf, ok := ret.Get(0).(func() math.Int); ok { r0 = rf() @@ -200,6 +244,10 @@ func (_m *StakingValidatorI) GetTokens() math.Int { func (_m *StakingValidatorI) IsBonded() bool { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for IsBonded") + } + var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() @@ -214,6 +262,10 @@ func (_m *StakingValidatorI) IsBonded() bool { func (_m *StakingValidatorI) IsJailed() bool { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for IsJailed") + } + var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() @@ -228,6 +280,10 @@ func (_m *StakingValidatorI) IsJailed() bool { func (_m *StakingValidatorI) IsUnbonded() bool { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for IsUnbonded") + } + var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() @@ -242,6 +298,10 @@ func (_m *StakingValidatorI) IsUnbonded() bool { func (_m *StakingValidatorI) IsUnbonding() bool { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for IsUnbonding") + } + var r0 bool if rf, ok := ret.Get(0).(func() bool); ok { r0 = rf() @@ -256,6 +316,10 @@ func (_m *StakingValidatorI) IsUnbonding() bool { func (_m *StakingValidatorI) SharesFromTokens(amt math.Int) (math.LegacyDec, error) { ret := _m.Called(amt) + if len(ret) == 0 { + panic("no return value specified for SharesFromTokens") + } + var r0 math.LegacyDec var r1 error if rf, ok := ret.Get(0).(func(math.Int) (math.LegacyDec, error)); ok { @@ -280,6 +344,10 @@ func (_m *StakingValidatorI) SharesFromTokens(amt math.Int) (math.LegacyDec, err func (_m *StakingValidatorI) SharesFromTokensTruncated(amt math.Int) (math.LegacyDec, error) { ret := _m.Called(amt) + if len(ret) == 0 { + panic("no return value specified for SharesFromTokensTruncated") + } + var r0 math.LegacyDec var r1 error if rf, ok := ret.Get(0).(func(math.Int) (math.LegacyDec, error)); ok { @@ -304,6 +372,10 @@ func (_m *StakingValidatorI) SharesFromTokensTruncated(amt math.Int) (math.Legac func (_m *StakingValidatorI) TmConsPublicKey() (crypto.PublicKey, error) { ret := _m.Called() + if len(ret) == 0 { + panic("no return value specified for TmConsPublicKey") + } + var r0 crypto.PublicKey var r1 error if rf, ok := ret.Get(0).(func() (crypto.PublicKey, error)); ok { @@ -328,6 +400,10 @@ func (_m *StakingValidatorI) TmConsPublicKey() (crypto.PublicKey, error) { func (_m *StakingValidatorI) TokensFromShares(_a0 math.LegacyDec) math.LegacyDec { ret := _m.Called(_a0) + if len(ret) == 0 { + panic("no return value specified for TokensFromShares") + } + var r0 math.LegacyDec if rf, ok := ret.Get(0).(func(math.LegacyDec) math.LegacyDec); ok { r0 = rf(_a0) @@ -342,6 +418,10 @@ func (_m *StakingValidatorI) TokensFromShares(_a0 math.LegacyDec) math.LegacyDec func (_m *StakingValidatorI) TokensFromSharesRoundUp(_a0 math.LegacyDec) math.LegacyDec { ret := _m.Called(_a0) + if len(ret) == 0 { + panic("no return value specified for TokensFromSharesRoundUp") + } + var r0 math.LegacyDec if rf, ok := ret.Get(0).(func(math.LegacyDec) math.LegacyDec); ok { r0 = rf(_a0) @@ -356,6 +436,10 @@ func (_m *StakingValidatorI) TokensFromSharesRoundUp(_a0 math.LegacyDec) math.Le func (_m *StakingValidatorI) TokensFromSharesTruncated(_a0 math.LegacyDec) math.LegacyDec { ret := _m.Called(_a0) + if len(ret) == 0 { + panic("no return value specified for TokensFromSharesTruncated") + } + var r0 math.LegacyDec if rf, ok := ret.Get(0).(func(math.LegacyDec) math.LegacyDec); ok { r0 = rf(_a0) @@ -371,8 +455,7 @@ func (_m *StakingValidatorI) TokensFromSharesTruncated(_a0 math.LegacyDec) math. func NewStakingValidatorI(t interface { mock.TestingT Cleanup(func()) -}, -) *StakingValidatorI { +}) *StakingValidatorI { mock := &StakingValidatorI{} mock.Mock.Test(t) From 3264303d37aa362d8175007be37bb3d07ef94e17 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Tue, 19 Dec 2023 12:00:27 +0530 Subject: [PATCH 03/18] chore: fixed keeper,ante files and app.go in paloma --- app/app.go | 11 +- testutil/keeper/paloma.go | 6 +- x/paloma/ante.go | 8 +- x/paloma/ante_test.go | 511 +++++++++++---------- x/paloma/keeper/grpc_query_params_test.go | 2 +- x/paloma/keeper/keeper.go | 6 +- x/paloma/keeper/keeper_integration_test.go | 39 +- 7 files changed, 294 insertions(+), 289 deletions(-) diff --git a/app/app.go b/app/app.go index ceebac18..ca4527e8 100644 --- a/app/app.go +++ b/app/app.go @@ -141,6 +141,7 @@ import ( evmmodulekeeper "github.com/palomachain/paloma/x/evm/keeper" evmmoduletypes "github.com/palomachain/paloma/x/evm/types" + palomamodule "github.com/palomachain/paloma/x/paloma" palomamodulekeeper "github.com/palomachain/paloma/x/paloma/keeper" palomamoduletypes "github.com/palomachain/paloma/x/paloma/types" schedulermodule "github.com/palomachain/paloma/x/scheduler" @@ -967,7 +968,7 @@ func New( app.SetEndBlocker(app.EndBlocker) /*baseAnteHandler*/ - _, err = ante.NewAnteHandler( + baseAnteHandler, err := ante.NewAnteHandler( ante.HandlerOptions{ AccountKeeper: app.AccountKeeper, BankKeeper: app.BankKeeper, @@ -982,11 +983,11 @@ func New( anteDecorators := []sdk.AnteDecorator{ palomamodule.NewAnteHandlerDecorator(baseAnteHandler), } - anteDecorators = append(anteDecorators) - palomamodule.NewLogMsgDecorator(app.appCodec), + anteDecorators = append(anteDecorators, + palomamodule.NewLogMsgDecorator(app.appCodec), palomamodule.NewVerifyAuthorisedSignatureDecorator(app.FeeGrantKeeper), - - anteHandler := sdk.ChainAnteDecorators( + ) + anteHandler := sdk.ChainAnteDecorators( anteDecorators..., ) diff --git a/testutil/keeper/paloma.go b/testutil/keeper/paloma.go index f7ff3cc5..2eaa1e95 100644 --- a/testutil/keeper/paloma.go +++ b/testutil/keeper/paloma.go @@ -1,6 +1,7 @@ package keeper import ( + "github.com/cosmos/cosmos-sdk/runtime" "testing" "cosmossdk.io/log" @@ -40,12 +41,11 @@ func PalomaKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { ) k := keeper.NewKeeper( cdc, - storeKey, - memStoreKey, + runtime.NewKVStoreService(storeKey), paramsSubspace, "v0.0.1", // do not use this PalomaKeeper function! valsetkeeper.Keeper{}, - nil, + nil, // nil to be replaced by upgrade keeper ) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) diff --git a/x/paloma/ante.go b/x/paloma/ante.go index aa9f640b..b2f1afd6 100644 --- a/x/paloma/ante.go +++ b/x/paloma/ante.go @@ -31,7 +31,7 @@ func NewAnteHandlerDecorator(handler sdk.AnteHandler) HandlerDecorator { } // AnteHandle wraps the next AnteHandler to perform custom pre- and post-processing -func (decorator HandlerDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx context.Context, err error) { +func (decorator HandlerDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { sdkCtx := sdk.UnwrapSDKContext(ctx) if newCtx, err = decorator.handler(sdkCtx, tx, simulate); err != nil { @@ -52,7 +52,7 @@ func NewLogMsgDecorator(cdc codec.Codec) LogMsgDecorator { } // AnteHandle logs all messages in blocks -func (d LogMsgDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (context.Context, error) { +func (d LogMsgDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) if simulate || sdkCtx.IsCheckTx() { @@ -84,7 +84,7 @@ func NewVerifyAuthorisedSignatureDecorator(fk types.FeegrantKeeper) VerifyAuthor // AnteHandle verifies that the message is signed by at least one signature that has // active fee grant from the creator address, IF the message contains metadata. -func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx context.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (context.Context, error) { +func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { sdkCtx := sdk.UnwrapSDKContext(ctx) if simulate { return next(sdkCtx, tx, simulate) @@ -134,7 +134,7 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx context.Context, tx s grantees := make([]string, 0, len(signers)) for _, signer := range signers { if v, found := grantsLkUp[signer]; found { - liblog.FromSDKLogger(logger(ctx)).WithFields( "signature", v.Grantee).Debug("found granted signature") + liblog.FromSDKLogger(logger(ctx)).WithFields("signature", v.Grantee).Debug("found granted signature") grantees = append(grantees, v.Grantee) } } diff --git a/x/paloma/ante_test.go b/x/paloma/ante_test.go index a71294cf..727692d3 100644 --- a/x/paloma/ante_test.go +++ b/x/paloma/ante_test.go @@ -1,257 +1,258 @@ package paloma_test -import ( - "context" - "fmt" - "reflect" - "testing" - - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/feegrant" - "github.com/palomachain/paloma/x/paloma" - "github.com/palomachain/paloma/x/paloma/types" - vtypes "github.com/palomachain/paloma/x/valset/types" - "github.com/stretchr/testify/require" -) - -type tx struct { - msgs []sdk.Msg -} - -func (t *tx) GetMsgs() []sdk.Msg { - return t.msgs -} - -func (t *tx) ValidateBasic() error { - return nil -} - -type feegrantKeeperCall struct { - expected *feegrant.QueryAllowancesByGranterRequest - response *feegrant.QueryAllowancesByGranterResponse - err error -} -type mockFeegrantKeeper struct { - t *testing.T - calls []feegrantKeeperCall - idx int -} - -func (m *mockFeegrantKeeper) addCall(req *feegrant.QueryAllowancesByGranterRequest, response *feegrant.QueryAllowancesByGranterResponse, err error) { - if m.calls == nil { - m.calls = make([]feegrantKeeperCall, 0) - } - - m.calls = append(m.calls, feegrantKeeperCall{ - expected: req, - response: response, - err: err, - }) -} - -func (m *mockFeegrantKeeper) AllowancesByGranter(ctx context.Context, req *feegrant.QueryAllowancesByGranterRequest) (*feegrant.QueryAllowancesByGranterResponse, error) { - if m.idx >= len(m.calls) { - m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - only expected %d calls", m.idx) - } - - call := m.calls[m.idx] - if !reflect.DeepEqual(req, call.expected) { - m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - expected: %v, got: %v", call.expected, req) - } - - m.idx++ - return call.response, call.err -} - -type mockMsg struct{} - -func (m *mockMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{} } -func (m *mockMsg) ValidateBasic() error { return nil } -func (m *mockMsg) ProtoMessage() {} -func (m *mockMsg) Reset() {} -func (m *mockMsg) String() string { return "foo" } - -func Test_VerifyAuthorisedSignatureDecorator(t *testing.T) { - for i, tt := range []struct { - err error - setup func(*mockFeegrantKeeper) sdk.Tx - name string - }{ - { - name: "with no msgs in tx", - setup: func(*mockFeegrantKeeper) sdk.Tx { - return &tx{} - }, - }, - { - name: "with msg without metadata", - setup: func(*mockFeegrantKeeper) sdk.Tx { - return &tx{ - msgs: []sdk.Msg{ - &mockMsg{}, - }, - } - }, - }, - { - name: "with msg signed by creator", - setup: func(*mockFeegrantKeeper) sdk.Tx { - valAddr := sdk.AccAddress("foo") - return &tx{ - msgs: []sdk.Msg{ - &types.MsgAddStatusUpdate{ - Creator: valAddr.String(), - Status: "bar", - Level: 0, - Metadata: vtypes.MsgMetadata{ - Creator: valAddr.String(), - Signers: []string{valAddr.String()}, - }, - }, - }, - } - }, - }, - { - name: "with msg signed by valid signature", - setup: func(k *mockFeegrantKeeper) sdk.Tx { - valAddr := sdk.AccAddress("foo") - grantee := sdk.AccAddress("bar") - k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, - &feegrant.QueryAllowancesByGranterResponse{ - Allowances: []*feegrant.Grant{ - { - Granter: valAddr.String(), - Grantee: grantee.String(), - }, - }, - }, - nil) - return &tx{ - msgs: []sdk.Msg{ - &types.MsgAddStatusUpdate{ - Creator: valAddr.String(), - Status: "bar", - Level: 0, - Metadata: vtypes.MsgMetadata{ - Creator: valAddr.String(), - Signers: []string{grantee.String()}, - }, - }, - }, - } - }, - }, - { - name: "with msg signed by multiple valid signatures", - setup: func(k *mockFeegrantKeeper) sdk.Tx { - valAddr := sdk.AccAddress("foo") - grantee := sdk.AccAddress("bar") - grantee2 := sdk.AccAddress("bar") - k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, - &feegrant.QueryAllowancesByGranterResponse{ - Allowances: []*feegrant.Grant{ - { - Granter: valAddr.String(), - Grantee: grantee.String(), - }, - { - Granter: valAddr.String(), - Grantee: grantee2.String(), - }, - }, - }, - nil) - return &tx{ - msgs: []sdk.Msg{ - &types.MsgAddStatusUpdate{ - Creator: valAddr.String(), - Status: "bar", - Level: 0, - Metadata: vtypes.MsgMetadata{ - Creator: valAddr.String(), - Signers: []string{grantee.String(), grantee2.String()}, - }, - }, - }, - } - }, - }, - { - name: "with msg signed by multiple signatures, including at least one valid signature", - setup: func(k *mockFeegrantKeeper) sdk.Tx { - valAddr := sdk.AccAddress("foo") - grantee := sdk.AccAddress("bar") - grantee2 := sdk.AccAddress("bar") - k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, - &feegrant.QueryAllowancesByGranterResponse{ - Allowances: []*feegrant.Grant{ - { - Granter: valAddr.String(), - Grantee: grantee.String(), - }, - }, - }, - nil) - return &tx{ - msgs: []sdk.Msg{ - &types.MsgAddStatusUpdate{ - Creator: valAddr.String(), - Status: "bar", - Level: 0, - Metadata: vtypes.MsgMetadata{ - Creator: valAddr.String(), - Signers: []string{grantee.String(), grantee2.String()}, - }, - }, - }, - } - }, - }, - { - name: "with msg signed by multiple signatures without at least one valid signature", - err: fmt.Errorf("no signature from granted address found for message"), - setup: func(k *mockFeegrantKeeper) sdk.Tx { - valAddr := sdk.AccAddress("foo") - grantee := sdk.AccAddress("bar") - grantee2 := sdk.AccAddress("bar") - k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, - &feegrant.QueryAllowancesByGranterResponse{ - Allowances: []*feegrant.Grant{}, - }, - nil) - return &tx{ - msgs: []sdk.Msg{ - &types.MsgAddStatusUpdate{ - Creator: valAddr.String(), - Status: "bar", - Level: 0, - Metadata: vtypes.MsgMetadata{ - Creator: valAddr.String(), - Signers: []string{grantee.String(), grantee2.String()}, - }, - }, - }, - } - }, - }, - } { - t.Run(fmt.Sprintf("%d. %s", i, tt.name), func(t *testing.T) { - r := require.New(t) - k := &mockFeegrantKeeper{t: t} - tx := tt.setup(k) - testee := paloma.NewVerifyAuthorisedSignatureDecorator(k) - ctx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) - _, err := testee.AnteHandle(ctx, tx, false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { return ctx, nil }) - - if tt.err != nil { - r.ErrorContains(err, tt.err.Error()) - } else { - r.NoError(err) - } - r.Len(k.calls, k.idx, "unexpected amount of calls") - }) - } -} +// +//import ( +// "context" +// "fmt" +// "reflect" +// "testing" +// +// "github.com/cometbft/cometbft/libs/log" +// tmproto "github.com/cometbft/cometbft/proto/tendermint/types" +// sdk "github.com/cosmos/cosmos-sdk/types" +// "github.com/cosmos/cosmos-sdk/x/feegrant" +// "github.com/palomachain/paloma/x/paloma" +// "github.com/palomachain/paloma/x/paloma/types" +// vtypes "github.com/palomachain/paloma/x/valset/types" +// "github.com/stretchr/testify/require" +//) +// +//type tx struct { +// msgs []sdk.Msg +//} +// +//func (t *tx) GetMsgs() []sdk.Msg { +// return t.msgs +//} +// +//func (t *tx) ValidateBasic() error { +// return nil +//} +// +//type feegrantKeeperCall struct { +// expected *feegrant.QueryAllowancesByGranterRequest +// response *feegrant.QueryAllowancesByGranterResponse +// err error +//} +//type mockFeegrantKeeper struct { +// t *testing.T +// calls []feegrantKeeperCall +// idx int +//} +// +//func (m *mockFeegrantKeeper) addCall(req *feegrant.QueryAllowancesByGranterRequest, response *feegrant.QueryAllowancesByGranterResponse, err error) { +// if m.calls == nil { +// m.calls = make([]feegrantKeeperCall, 0) +// } +// +// m.calls = append(m.calls, feegrantKeeperCall{ +// expected: req, +// response: response, +// err: err, +// }) +//} +// +//func (m *mockFeegrantKeeper) AllowancesByGranter(ctx context.Context, req *feegrant.QueryAllowancesByGranterRequest) (*feegrant.QueryAllowancesByGranterResponse, error) { +// if m.idx >= len(m.calls) { +// m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - only expected %d calls", m.idx) +// } +// +// call := m.calls[m.idx] +// if !reflect.DeepEqual(req, call.expected) { +// m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - expected: %v, got: %v", call.expected, req) +// } +// +// m.idx++ +// return call.response, call.err +//} +// +//type mockMsg struct{} +// +//func (m *mockMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{} } +//func (m *mockMsg) ValidateBasic() error { return nil } +//func (m *mockMsg) ProtoMessage() {} +//func (m *mockMsg) Reset() {} +//func (m *mockMsg) String() string { return "foo" } +// +//func Test_VerifyAuthorisedSignatureDecorator(t *testing.T) { +// for i, tt := range []struct { +// err error +// setup func(*mockFeegrantKeeper) sdk.Tx +// name string +// }{ +// { +// name: "with no msgs in tx", +// setup: func(*mockFeegrantKeeper) sdk.Tx { +// return &tx{} +// }, +// }, +// { +// name: "with msg without metadata", +// setup: func(*mockFeegrantKeeper) sdk.Tx { +// return &tx{ +// msgs: []sdk.Msg{ +// &mockMsg{}, +// }, +// } +// }, +// }, +// { +// name: "with msg signed by creator", +// setup: func(*mockFeegrantKeeper) sdk.Tx { +// valAddr := sdk.AccAddress("foo") +// return &tx{ +// msgs: []sdk.Msg{ +// &types.MsgAddStatusUpdate{ +// Creator: valAddr.String(), +// Status: "bar", +// Level: 0, +// Metadata: vtypes.MsgMetadata{ +// Creator: valAddr.String(), +// Signers: []string{valAddr.String()}, +// }, +// }, +// }, +// } +// }, +// }, +// { +// name: "with msg signed by valid signature", +// setup: func(k *mockFeegrantKeeper) sdk.Tx { +// valAddr := sdk.AccAddress("foo") +// grantee := sdk.AccAddress("bar") +// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, +// &feegrant.QueryAllowancesByGranterResponse{ +// Allowances: []*feegrant.Grant{ +// { +// Granter: valAddr.String(), +// Grantee: grantee.String(), +// }, +// }, +// }, +// nil) +// return &tx{ +// msgs: []sdk.Msg{ +// &types.MsgAddStatusUpdate{ +// Creator: valAddr.String(), +// Status: "bar", +// Level: 0, +// Metadata: vtypes.MsgMetadata{ +// Creator: valAddr.String(), +// Signers: []string{grantee.String()}, +// }, +// }, +// }, +// } +// }, +// }, +// { +// name: "with msg signed by multiple valid signatures", +// setup: func(k *mockFeegrantKeeper) sdk.Tx { +// valAddr := sdk.AccAddress("foo") +// grantee := sdk.AccAddress("bar") +// grantee2 := sdk.AccAddress("bar") +// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, +// &feegrant.QueryAllowancesByGranterResponse{ +// Allowances: []*feegrant.Grant{ +// { +// Granter: valAddr.String(), +// Grantee: grantee.String(), +// }, +// { +// Granter: valAddr.String(), +// Grantee: grantee2.String(), +// }, +// }, +// }, +// nil) +// return &tx{ +// msgs: []sdk.Msg{ +// &types.MsgAddStatusUpdate{ +// Creator: valAddr.String(), +// Status: "bar", +// Level: 0, +// Metadata: vtypes.MsgMetadata{ +// Creator: valAddr.String(), +// Signers: []string{grantee.String(), grantee2.String()}, +// }, +// }, +// }, +// } +// }, +// }, +// { +// name: "with msg signed by multiple signatures, including at least one valid signature", +// setup: func(k *mockFeegrantKeeper) sdk.Tx { +// valAddr := sdk.AccAddress("foo") +// grantee := sdk.AccAddress("bar") +// grantee2 := sdk.AccAddress("bar") +// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, +// &feegrant.QueryAllowancesByGranterResponse{ +// Allowances: []*feegrant.Grant{ +// { +// Granter: valAddr.String(), +// Grantee: grantee.String(), +// }, +// }, +// }, +// nil) +// return &tx{ +// msgs: []sdk.Msg{ +// &types.MsgAddStatusUpdate{ +// Creator: valAddr.String(), +// Status: "bar", +// Level: 0, +// Metadata: vtypes.MsgMetadata{ +// Creator: valAddr.String(), +// Signers: []string{grantee.String(), grantee2.String()}, +// }, +// }, +// }, +// } +// }, +// }, +// { +// name: "with msg signed by multiple signatures without at least one valid signature", +// err: fmt.Errorf("no signature from granted address found for message"), +// setup: func(k *mockFeegrantKeeper) sdk.Tx { +// valAddr := sdk.AccAddress("foo") +// grantee := sdk.AccAddress("bar") +// grantee2 := sdk.AccAddress("bar") +// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, +// &feegrant.QueryAllowancesByGranterResponse{ +// Allowances: []*feegrant.Grant{}, +// }, +// nil) +// return &tx{ +// msgs: []sdk.Msg{ +// &types.MsgAddStatusUpdate{ +// Creator: valAddr.String(), +// Status: "bar", +// Level: 0, +// Metadata: vtypes.MsgMetadata{ +// Creator: valAddr.String(), +// Signers: []string{grantee.String(), grantee2.String()}, +// }, +// }, +// }, +// } +// }, +// }, +// } { +// t.Run(fmt.Sprintf("%d. %s", i, tt.name), func(t *testing.T) { +// r := require.New(t) +// k := &mockFeegrantKeeper{t: t} +// tx := tt.setup(k) +// testee := paloma.NewVerifyAuthorisedSignatureDecorator(k) +// ctx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) +// _, err := testee.AnteHandle(ctx, tx, false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { return ctx, nil }) +// +// if tt.err != nil { +// r.ErrorContains(err, tt.err.Error()) +// } else { +// r.NoError(err) +// } +// r.Len(k.calls, k.idx, "unexpected amount of calls") +// }) +// } +//} diff --git a/x/paloma/keeper/grpc_query_params_test.go b/x/paloma/keeper/grpc_query_params_test.go index 7a3a8f18..f4589ea6 100644 --- a/x/paloma/keeper/grpc_query_params_test.go +++ b/x/paloma/keeper/grpc_query_params_test.go @@ -11,7 +11,7 @@ import ( func TestParamsQuery(t *testing.T) { keeper, ctx := testkeeper.PalomaKeeper(t) - wctx := sdk.WrapSDKContext(ctx) + wctx := sdk.UnwrapSDKContext(ctx) params := types.DefaultParams() keeper.SetParams(ctx, params) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index da97020f..727c98b1 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -26,7 +26,7 @@ type ( Valset types.ValsetKeeper Upgrade types.UpgradeKeeper AppVersion string - addressCodec address.Codec + AddressCodec address.Codec ExternalChains []types.ExternalChainSupporterKeeper } ) @@ -83,7 +83,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) var g whoops.Group for _, val := range vals { - bz, err := k.addressCodec.StringToBytes(val.GetOperator()) + bz, err := k.AddressCodec.StringToBytes(val.GetOperator()) if err != nil { return err } @@ -108,7 +108,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - bz, err = k.addressCodec.StringToBytes(val.GetOperator()) + bz, err = k.AddressCodec.StringToBytes(val.GetOperator()) if err != nil { return err } diff --git a/x/paloma/keeper/keeper_integration_test.go b/x/paloma/keeper/keeper_integration_test.go index f349f103..c0d789f9 100644 --- a/x/paloma/keeper/keeper_integration_test.go +++ b/x/paloma/keeper/keeper_integration_test.go @@ -2,13 +2,13 @@ package keeper_test import ( "fmt" + keeperutil "github.com/palomachain/paloma/util/keeper" "math/big" "testing" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + upgradetypes "cosmossdk.io/x/upgrade/types" sdk "github.com/cosmos/cosmos-sdk/types" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/palomachain/paloma/app" @@ -33,9 +33,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() BeforeEach(func() { t := GinkgoT() a = app.NewTestApp(t, false) - ctx = a.NewContext(false, tmproto.Header{ - Height: 5, - }) + ctx = a.NewContext(false).WithBlockHeight(5) k = &a.PalomaKeeper }) @@ -56,7 +54,8 @@ var _ = Describe("jailing validators with missing external chain infos", func() // val[1] has only one chain // val[2] doesn't have anything // All other vals have everything - err := a.ValsetKeeper.AddExternalChainInfo(ctx, vals[0].GetOperator(), []*valsettypes.ExternalChainInfo{ + valAddress, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[0].GetOperator()) + err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", ChainReferenceID: "c1", @@ -71,7 +70,8 @@ var _ = Describe("jailing validators with missing external chain infos", func() }, }) Expect(err).To(BeNil()) - err = a.ValsetKeeper.AddExternalChainInfo(ctx, vals[1].GetOperator(), []*valsettypes.ExternalChainInfo{ + valAddress2, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[1].GetOperator()) + err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress2, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", ChainReferenceID: "c1", @@ -81,7 +81,8 @@ var _ = Describe("jailing validators with missing external chain infos", func() }) Expect(err).To(BeNil()) for i, v := range vals[3:] { - err := a.ValsetKeeper.AddExternalChainInfo(ctx, v.GetOperator(), []*valsettypes.ExternalChainInfo{ + valAddress, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, v.GetOperator()) + err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", ChainReferenceID: "c1", @@ -108,18 +109,21 @@ var _ = Describe("jailing validators with missing external chain infos", func() It("jails val[1] and val[2], but no val[0]", func() { By("validators are not jailed") - Expect(a.ValsetKeeper.IsJailed(ctx, vals[0].GetOperator())).To(BeFalse()) - Expect(a.ValsetKeeper.IsJailed(ctx, vals[1].GetOperator())).To(BeFalse()) - Expect(a.ValsetKeeper.IsJailed(ctx, vals[2].GetOperator())).To(BeFalse()) + valAddress1, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[0].GetOperator()) + valAddress2, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[1].GetOperator()) + valAddress3, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[2].GetOperator()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress1)).To(BeFalse()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress2)).To(BeFalse()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress3)).To(BeFalse()) By("jail validators with missing external chain infos") - err := k.JailValidatorsWithMissingExternalChainInfos(ctx) + err = k.JailValidatorsWithMissingExternalChainInfos(ctx) Expect(err).To(BeNil()) By("check for jailed validators") - Expect(a.ValsetKeeper.IsJailed(ctx, vals[0].GetOperator())).To(BeFalse()) - Expect(a.ValsetKeeper.IsJailed(ctx, vals[1].GetOperator())).To(BeTrue()) - Expect(a.ValsetKeeper.IsJailed(ctx, vals[2].GetOperator())).To(BeTrue()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress1)).To(BeFalse()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress2)).To(BeTrue()) + Expect(a.ValsetKeeper.IsJailed(ctx, valAddress3)).To(BeTrue()) }) }) }) @@ -132,9 +136,8 @@ var _ = Describe("checking the chain version", func() { BeforeEach(func() { t := GinkgoT() a = app.NewTestApp(t, false) - ctx = a.NewContext(false, tmproto.Header{ - Height: 5, - }) + ctx = a.NewContext(false).WithBlockHeight(5) + k = &a.PalomaKeeper }) From c888245c563c0505a05b39fb4877b04e507350ae Mon Sep 17 00:00:00 2001 From: Deepan kumar <150890063+deepan95dev@users.noreply.github.com> Date: Tue, 19 Dec 2023 15:04:30 +0530 Subject: [PATCH 04/18] chore: removed comment in testutil/paloma --- testutil/keeper/paloma.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testutil/keeper/paloma.go b/testutil/keeper/paloma.go index 2eaa1e95..bf8586cc 100644 --- a/testutil/keeper/paloma.go +++ b/testutil/keeper/paloma.go @@ -45,7 +45,7 @@ func PalomaKeeper(t testing.TB) (*keeper.Keeper, sdk.Context) { paramsSubspace, "v0.0.1", // do not use this PalomaKeeper function! valsetkeeper.Keeper{}, - nil, // nil to be replaced by upgrade keeper + nil, ) ctx := sdk.NewContext(stateStore, tmproto.Header{}, false, log.NewNopLogger()) From 729f83611bec75d58cc4bdb0770af60772e9b848 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Tue, 19 Dec 2023 17:52:06 +0530 Subject: [PATCH 05/18] chore: reviewed changes in ante.go and libmeta --- util/libmeta/get_signers.go | 1 + x/paloma/ante.go | 39 ++++++++++++++++--------------------- x/paloma/keeper/keeper.go | 5 +++-- 3 files changed, 21 insertions(+), 24 deletions(-) diff --git a/util/libmeta/get_signers.go b/util/libmeta/get_signers.go index 8120b469..15f7af34 100644 --- a/util/libmeta/get_signers.go +++ b/util/libmeta/get_signers.go @@ -11,6 +11,7 @@ type Metadata interface { type MsgWithMetadata[T Metadata] interface { GetMetadata() T + GetSigners() []string } func GetSigners[E Metadata, T MsgWithMetadata[E]](msg T) []sdk.AccAddress { diff --git a/x/paloma/ante.go b/x/paloma/ante.go index b2f1afd6..6504dd30 100644 --- a/x/paloma/ante.go +++ b/x/paloma/ante.go @@ -3,13 +3,13 @@ package paloma import ( "context" "fmt" + "github.com/palomachain/paloma/util/liblog" "cosmossdk.io/log" "cosmossdk.io/x/feegrant" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/gogo/protobuf/proto" - "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/util/libmeta" "github.com/palomachain/paloma/x/paloma/types" vtypes "github.com/palomachain/paloma/x/valset/types" @@ -32,13 +32,11 @@ func NewAnteHandlerDecorator(handler sdk.AnteHandler) HandlerDecorator { // AnteHandle wraps the next AnteHandler to perform custom pre- and post-processing func (decorator HandlerDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (newCtx sdk.Context, err error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - - if newCtx, err = decorator.handler(sdkCtx, tx, simulate); err != nil { + if newCtx, err = decorator.handler(ctx, tx, simulate); err != nil { return newCtx, err } - return next(sdkCtx, tx, simulate) + return next(newCtx, tx, simulate) } // LogMsgDecorator logs all messages in blocks @@ -53,23 +51,21 @@ func NewLogMsgDecorator(cdc codec.Codec) LogMsgDecorator { // AnteHandle logs all messages in blocks func (d LogMsgDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) - - if simulate || sdkCtx.IsCheckTx() { - return next(sdkCtx, tx, simulate) + if simulate || ctx.IsCheckTx() { + return next(ctx, tx, simulate) } msgs := tx.GetMsgs() for _, msg := range msgs { - liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("received message of type %s in block %d: %s", + logger(ctx).Debug(fmt.Sprintf("received message of type %s in block %d: %s", proto.MessageName(msg), - sdkCtx.BlockHeight(), + ctx.BlockHeight(), string(d.cdc.MustMarshalJSON(msg)), )) } - return next(sdkCtx, tx, simulate) + return next(ctx, tx, simulate) } // VerifyAuthorisedSignatureDecorator verifies that the message is signed by at least one signature that has @@ -85,20 +81,19 @@ func NewVerifyAuthorisedSignatureDecorator(fk types.FeegrantKeeper) VerifyAuthor // AnteHandle verifies that the message is signed by at least one signature that has // active fee grant from the creator address, IF the message contains metadata. func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.Tx, simulate bool, next sdk.AnteHandler) (sdk.Context, error) { - sdkCtx := sdk.UnwrapSDKContext(ctx) if simulate { - return next(sdkCtx, tx, simulate) + return next(ctx, tx, simulate) } for _, msg := range tx.GetMsgs() { m, ok := msg.(libmeta.MsgWithMetadata[vtypes.MsgMetadata]) if !ok { - liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("msg %s does not contain metadata. skipping ownership verification...", proto.MessageName(msg))) + logger(ctx).Debug(fmt.Sprintf("msg %s does not contain metadata. skipping ownership verification...", proto.MessageName(msg))) continue } creator := m.GetMetadata().GetCreator() - signers := m.GetMetadata().GetSigners() + signers := m.GetSigners() signedByCreator := func() bool { for _, v := range signers { @@ -109,7 +104,7 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T return false }() if signedByCreator { - liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("msg %s was signed by creator.", proto.MessageName(msg))) + logger(ctx).Debug(fmt.Sprintf("msg %s was signed by creator.", proto.MessageName(msg))) continue } @@ -120,21 +115,21 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T return ctx, fmt.Errorf("failed to verify message signature authorisation: %w", err) } - liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("got %d allowances from granter %s", len(grants.GetAllowances()), creator)) + logger(ctx).Debug(fmt.Sprintf("got %d allowances from granter %s", len(grants.GetAllowances()), creator)) grantsLkUp := map[string]feegrant.Grant{} for _, v := range grants.GetAllowances() { if v == nil { continue } - liblog.FromSDKLogger(logger(ctx)).WithFields("granter", v.GetGranter(), "grantee", v.GetGrantee()).Debug("found allowance") + logger(ctx).Debug("found allowance", "granter", v.GetGranter(), "grantee", v.GetGrantee()) grantsLkUp[v.GetGrantee()] = *v } grantees := make([]string, 0, len(signers)) for _, signer := range signers { if v, found := grantsLkUp[signer]; found { - liblog.FromSDKLogger(logger(ctx)).WithFields("signature", v.Grantee).Debug("found granted signature") + logger(ctx).Debug("found granted signature", "signature", v.Grantee) grantees = append(grantees, v.Grantee) } } @@ -143,8 +138,8 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T return ctx, fmt.Errorf("no signature from granted address found for message %s", proto.MessageName(msg)) } - liblog.FromSDKLogger(logger(ctx)).Debug(fmt.Sprintf("found total of %d signatures from granted addresses for message %s", len(grantees), proto.MessageName(msg))) + logger(ctx).Debug(fmt.Sprintf("found total of %d signatures from granted addresses for message %s", len(grantees), proto.MessageName(msg))) } - return next(sdkCtx, tx, simulate) + return next(ctx, tx, simulate) } diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 727c98b1..b39e4f44 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -3,6 +3,7 @@ package keeper import ( "context" "fmt" + keeperutil "github.com/palomachain/paloma/util/keeper" "sort" "strings" @@ -83,7 +84,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) var g whoops.Group for _, val := range vals { - bz, err := k.AddressCodec.StringToBytes(val.GetOperator()) + bz, err := keeperutil.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) if err != nil { return err } @@ -108,7 +109,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - bz, err = k.AddressCodec.StringToBytes(val.GetOperator()) + bz, err = keeperutil.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) if err != nil { return err } From df3afaa86120575a2f537cc57bd47e4314d6c3fc Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Thu, 21 Dec 2023 12:09:36 +0530 Subject: [PATCH 06/18] chore: valset uncommented in palomaKeeper --- app/app.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/app.go b/app/app.go index ca4527e8..7b9510b2 100644 --- a/app/app.go +++ b/app/app.go @@ -617,7 +617,7 @@ func New( runtime.NewKVStoreService(keys[palomamoduletypes.StoreKey]), app.GetSubspace(palomamoduletypes.ModuleName), semverVersion, - nil, //app.ValsetKeeper (TODO), + app.ValsetKeeper, app.PalomaKeeper.Upgrade, ) From 8eb2e52916a87bdb5454c8ac294bbc29deab9856 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Tue, 26 Dec 2023 15:59:37 +0530 Subject: [PATCH 07/18] chore: moved StringToBytes function to local keeper --- x/paloma/keeper/keeper.go | 24 +++++++++++++++++----- x/paloma/keeper/keeper_integration_test.go | 13 ++++++------ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index b39e4f44..cc5701b2 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -3,13 +3,13 @@ package keeper import ( "context" "fmt" - keeperutil "github.com/palomachain/paloma/util/keeper" + "log" "sort" "strings" "cosmossdk.io/core/address" cosmosstore "cosmossdk.io/core/store" - "cosmossdk.io/log" + cosmoslog "cosmossdk.io/log" "github.com/VolumeFi/whoops" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" @@ -63,7 +63,21 @@ func NewKeeper( } } -func (k Keeper) Logger(ctx context.Context) log.Logger { +func (k *Keeper) MustGetValAddr(addr string) (sdk.ValAddress, error) { + defer func() { + if r := recover(); r != nil { + log.Printf("error while getting valAddr ", r) + return + } + }() + bz, err := k.AddressCodec.StringToBytes(addr) + if err != nil { + panic(err) + } + return bz, err +} + +func (k Keeper) Logger(ctx context.Context) cosmoslog.Logger { sdkCtx := sdk.UnwrapSDKContext(ctx) return liblog.FromSDKLogger(sdkCtx.Logger()).With("module", fmt.Sprintf("x/%s", types.ModuleName)) } @@ -84,7 +98,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) var g whoops.Group for _, val := range vals { - bz, err := keeperutil.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) + bz, err := k.MustGetValAddr(val.GetOperator()) if err != nil { return err } @@ -109,7 +123,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - bz, err = keeperutil.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) + bz, err = k.MustGetValAddr(val.GetOperator()) if err != nil { return err } diff --git a/x/paloma/keeper/keeper_integration_test.go b/x/paloma/keeper/keeper_integration_test.go index c0d789f9..73600d7c 100644 --- a/x/paloma/keeper/keeper_integration_test.go +++ b/x/paloma/keeper/keeper_integration_test.go @@ -2,7 +2,6 @@ package keeper_test import ( "fmt" - keeperutil "github.com/palomachain/paloma/util/keeper" "math/big" "testing" @@ -54,7 +53,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() // val[1] has only one chain // val[2] doesn't have anything // All other vals have everything - valAddress, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[0].GetOperator()) + valAddress, err := k.MustGetValAddr(vals[0].GetOperator()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -70,7 +69,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() }, }) Expect(err).To(BeNil()) - valAddress2, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[1].GetOperator()) + valAddress2, err := k.MustGetValAddr(vals[1].GetOperator()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress2, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -81,7 +80,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() }) Expect(err).To(BeNil()) for i, v := range vals[3:] { - valAddress, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, v.GetOperator()) + valAddress, err := k.MustGetValAddr(v.GetOperator()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -109,9 +108,9 @@ var _ = Describe("jailing validators with missing external chain infos", func() It("jails val[1] and val[2], but no val[0]", func() { By("validators are not jailed") - valAddress1, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[0].GetOperator()) - valAddress2, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[1].GetOperator()) - valAddress3, err := keeperutil.ValAddressFromBech32(a.PalomaKeeper.AddressCodec, vals[2].GetOperator()) + valAddress1, err := k.MustGetValAddr(vals[0].GetOperator()) + valAddress2, err := k.MustGetValAddr(vals[1].GetOperator()) + valAddress3, err := k.MustGetValAddr(vals[2].GetOperator()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress1)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress2)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress3)).To(BeFalse()) From 643edb50a8750f6be1716e9b8f47f523955ae412 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Wed, 27 Dec 2023 11:12:22 +0530 Subject: [PATCH 08/18] chore: removed error return in mustGetValAddr function --- x/paloma/keeper/keeper.go | 36 ++++++++++++++---------------------- 1 file changed, 14 insertions(+), 22 deletions(-) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index cc5701b2..79afe2d5 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -63,20 +63,6 @@ func NewKeeper( } } -func (k *Keeper) MustGetValAddr(addr string) (sdk.ValAddress, error) { - defer func() { - if r := recover(); r != nil { - log.Printf("error while getting valAddr ", r) - return - } - }() - bz, err := k.AddressCodec.StringToBytes(addr) - if err != nil { - panic(err) - } - return bz, err -} - func (k Keeper) Logger(ctx context.Context) cosmoslog.Logger { sdkCtx := sdk.UnwrapSDKContext(ctx) return liblog.FromSDKLogger(sdkCtx.Logger()).With("module", fmt.Sprintf("x/%s", types.ModuleName)) @@ -98,10 +84,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) var g whoops.Group for _, val := range vals { - bz, err := k.MustGetValAddr(val.GetOperator()) - if err != nil { - return err - } + bz := k.MustGetValAddr(val.GetOperator()) exts, err := k.Valset.GetValidatorChainInfos(ctx, bz) if err != nil { g.Add(err) @@ -123,10 +106,7 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - bz, err = k.MustGetValAddr(val.GetOperator()) - if err != nil { - return err - } + bz = k.MustGetValAddr(val.GetOperator()) if len(notSupported) > 0 { g.Add(k.Valset.Jail(ctx, bz, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) } @@ -176,3 +156,15 @@ func (k Keeper) CheckChainVersion(ctx context.Context) { return } } +func (k *Keeper) MustGetValAddr(addr string) sdk.ValAddress { + defer func() { + if r := recover(); r != nil { + log.Printf("error while getting valAddr ", r) + } + }() + bz, err := k.AddressCodec.StringToBytes(addr) + if err != nil { + panic(err) + } + return bz +} From db20620861a1e92f463ea45831665c941054e583 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Wed, 27 Dec 2023 11:22:06 +0530 Subject: [PATCH 09/18] chore: used liblog in mustGetValAddr function --- x/paloma/keeper/keeper.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 79afe2d5..ee8b9668 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -3,7 +3,6 @@ package keeper import ( "context" "fmt" - "log" "sort" "strings" @@ -159,7 +158,7 @@ func (k Keeper) CheckChainVersion(ctx context.Context) { func (k *Keeper) MustGetValAddr(addr string) sdk.ValAddress { defer func() { if r := recover(); r != nil { - log.Printf("error while getting valAddr ", r) + k.Logger(context.Background()).Error("error while getting valAddr") } }() bz, err := k.AddressCodec.StringToBytes(addr) From 0d7aeb48dae589ce4d568bf9f457b1448cbc3af8 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Thu, 28 Dec 2023 10:15:56 +0530 Subject: [PATCH 10/18] chore: reviewed changes in paloma and util --- util/libmeta/get_signers.go | 1 - x/paloma/keeper/keeper.go | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/util/libmeta/get_signers.go b/util/libmeta/get_signers.go index 15f7af34..8120b469 100644 --- a/util/libmeta/get_signers.go +++ b/util/libmeta/get_signers.go @@ -11,7 +11,6 @@ type Metadata interface { type MsgWithMetadata[T Metadata] interface { GetMetadata() T - GetSigners() []string } func GetSigners[E Metadata, T MsgWithMetadata[E]](msg T) []sdk.AccAddress { diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index ee8b9668..838d2142 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -158,7 +158,7 @@ func (k Keeper) CheckChainVersion(ctx context.Context) { func (k *Keeper) MustGetValAddr(addr string) sdk.ValAddress { defer func() { if r := recover(); r != nil { - k.Logger(context.Background()).Error("error while getting valAddr") + k.Logger(context.Background()).Error("error while getting valAddr", r) } }() bz, err := k.AddressCodec.StringToBytes(addr) From 300b527780ce627ad70534afbfd31b42b3529914 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Thu, 28 Dec 2023 10:26:38 +0530 Subject: [PATCH 11/18] chore: reviewed changes in ante.go --- x/paloma/ante.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x/paloma/ante.go b/x/paloma/ante.go index 6504dd30..5372035a 100644 --- a/x/paloma/ante.go +++ b/x/paloma/ante.go @@ -93,7 +93,7 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T } creator := m.GetMetadata().GetCreator() - signers := m.GetSigners() + signers := m.GetMetadata().GetSigners() signedByCreator := func() bool { for _, v := range signers { From 226a01f7004b1acb5c9e8f3ddd23e5e288d2424c Mon Sep 17 00:00:00 2001 From: vishal Date: Thu, 4 Jan 2024 11:43:48 +0530 Subject: [PATCH 12/18] chore: created util function to get valAddress as per review comments --- util/keeper/address.go | 18 +++++++++++-- x/paloma/keeper/keeper.go | 27 ++++++++----------- x/paloma/keeper/keeper_integration_test.go | 31 +++++++++++++++++----- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/util/keeper/address.go b/util/keeper/address.go index 7e2fa21b..9b9ed050 100644 --- a/util/keeper/address.go +++ b/util/keeper/address.go @@ -1,8 +1,22 @@ package keeper -import "cosmossdk.io/core/address" +import ( + "errors" + "cosmossdk.io/core/address" +) + +type err string + +const ErrFailedToParseValAddress err = "failed to parse validator address from bech32" + +func (e err) Error() string { + return string(e) +} func ValAddressFromBech32(addressCodec address.Codec, valAddr string) ([]byte, error) { bz, err := addressCodec.StringToBytes(valAddr) - return bz, err + if err != nil { + return nil, errors.Join(ErrFailedToParseValAddress, err) + } + return bz, nil } diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 838d2142..e7903a82 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -13,6 +13,7 @@ import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + utilkeeper "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/util/liblog" "github.com/palomachain/paloma/x/paloma/types" "golang.org/x/mod/semver" @@ -83,8 +84,11 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) var g whoops.Group for _, val := range vals { - bz := k.MustGetValAddr(val.GetOperator()) - exts, err := k.Valset.GetValidatorChainInfos(ctx, bz) + valAddr, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } + exts, err := k.Valset.GetValidatorChainInfos(ctx, valAddr) if err != nil { g.Add(err) continue @@ -105,9 +109,12 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - bz = k.MustGetValAddr(val.GetOperator()) + valAddr, err = utilkeeper.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } if len(notSupported) > 0 { - g.Add(k.Valset.Jail(ctx, bz, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) + g.Add(k.Valset.Jail(ctx, valAddr, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) } } @@ -155,15 +162,3 @@ func (k Keeper) CheckChainVersion(ctx context.Context) { return } } -func (k *Keeper) MustGetValAddr(addr string) sdk.ValAddress { - defer func() { - if r := recover(); r != nil { - k.Logger(context.Background()).Error("error while getting valAddr", r) - } - }() - bz, err := k.AddressCodec.StringToBytes(addr) - if err != nil { - panic(err) - } - return bz -} diff --git a/x/paloma/keeper/keeper_integration_test.go b/x/paloma/keeper/keeper_integration_test.go index 73600d7c..c63847c8 100644 --- a/x/paloma/keeper/keeper_integration_test.go +++ b/x/paloma/keeper/keeper_integration_test.go @@ -12,6 +12,7 @@ import ( . "github.com/onsi/gomega" "github.com/palomachain/paloma/app" "github.com/palomachain/paloma/testutil" + utilkeeper "github.com/palomachain/paloma/util/keeper" "github.com/palomachain/paloma/x/paloma/keeper" valsettypes "github.com/palomachain/paloma/x/valset/types" ) @@ -53,7 +54,10 @@ var _ = Describe("jailing validators with missing external chain infos", func() // val[1] has only one chain // val[2] doesn't have anything // All other vals have everything - valAddress, err := k.MustGetValAddr(vals[0].GetOperator()) + valAddress, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[0].GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -69,7 +73,10 @@ var _ = Describe("jailing validators with missing external chain infos", func() }, }) Expect(err).To(BeNil()) - valAddress2, err := k.MustGetValAddr(vals[1].GetOperator()) + valAddress2, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[1].GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress2, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -80,7 +87,10 @@ var _ = Describe("jailing validators with missing external chain infos", func() }) Expect(err).To(BeNil()) for i, v := range vals[3:] { - valAddress, err := k.MustGetValAddr(v.GetOperator()) + valAddress, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, v.GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -108,9 +118,18 @@ var _ = Describe("jailing validators with missing external chain infos", func() It("jails val[1] and val[2], but no val[0]", func() { By("validators are not jailed") - valAddress1, err := k.MustGetValAddr(vals[0].GetOperator()) - valAddress2, err := k.MustGetValAddr(vals[1].GetOperator()) - valAddress3, err := k.MustGetValAddr(vals[2].GetOperator()) + valAddress1, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[0].GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } + valAddress2, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[1].GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } + valAddress3, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[2].GetOperator()) + if err != nil { + k.Logger(ctx).Error("Error while getting ValAddress", err) + } Expect(a.ValsetKeeper.IsJailed(ctx, valAddress1)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress2)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress3)).To(BeFalse()) From ab8c403e9abb61de2d4332e75533e8bdd1836128 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Thu, 4 Jan 2024 15:30:42 +0530 Subject: [PATCH 13/18] chore: GetSigners usage moved to libmeta --- x/paloma/ante.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x/paloma/ante.go b/x/paloma/ante.go index 5372035a..5f4da49f 100644 --- a/x/paloma/ante.go +++ b/x/paloma/ante.go @@ -93,11 +93,11 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T } creator := m.GetMetadata().GetCreator() - signers := m.GetMetadata().GetSigners() + signers := libmeta.GetSigners(m) signedByCreator := func() bool { for _, v := range signers { - if v == creator { + if v.String() == creator { return true } } @@ -128,7 +128,7 @@ func (d VerifyAuthorisedSignatureDecorator) AnteHandle(ctx sdk.Context, tx sdk.T grantees := make([]string, 0, len(signers)) for _, signer := range signers { - if v, found := grantsLkUp[signer]; found { + if v, found := grantsLkUp[signer.String()]; found { logger(ctx).Debug("found granted signature", "signature", v.Grantee) grantees = append(grantees, v.Grantee) } From ad08cb4fbff4ff7c4f011666132a6f1ec1dca441 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Mon, 8 Jan 2024 10:48:19 +0530 Subject: [PATCH 14/18] chore: logged, returned, asserted error from valAddress, ante_test retained --- x/paloma/ante_test.go | 511 ++++++++++----------- x/paloma/keeper/keeper.go | 3 +- x/paloma/keeper/keeper_integration_test.go | 24 +- 3 files changed, 263 insertions(+), 275 deletions(-) diff --git a/x/paloma/ante_test.go b/x/paloma/ante_test.go index 727692d3..3e3f0053 100644 --- a/x/paloma/ante_test.go +++ b/x/paloma/ante_test.go @@ -1,258 +1,257 @@ package paloma_test -// -//import ( -// "context" -// "fmt" -// "reflect" -// "testing" -// -// "github.com/cometbft/cometbft/libs/log" -// tmproto "github.com/cometbft/cometbft/proto/tendermint/types" -// sdk "github.com/cosmos/cosmos-sdk/types" -// "github.com/cosmos/cosmos-sdk/x/feegrant" -// "github.com/palomachain/paloma/x/paloma" -// "github.com/palomachain/paloma/x/paloma/types" -// vtypes "github.com/palomachain/paloma/x/valset/types" -// "github.com/stretchr/testify/require" -//) -// -//type tx struct { -// msgs []sdk.Msg -//} -// -//func (t *tx) GetMsgs() []sdk.Msg { -// return t.msgs -//} -// -//func (t *tx) ValidateBasic() error { -// return nil -//} -// -//type feegrantKeeperCall struct { -// expected *feegrant.QueryAllowancesByGranterRequest -// response *feegrant.QueryAllowancesByGranterResponse -// err error -//} -//type mockFeegrantKeeper struct { -// t *testing.T -// calls []feegrantKeeperCall -// idx int -//} -// -//func (m *mockFeegrantKeeper) addCall(req *feegrant.QueryAllowancesByGranterRequest, response *feegrant.QueryAllowancesByGranterResponse, err error) { -// if m.calls == nil { -// m.calls = make([]feegrantKeeperCall, 0) -// } -// -// m.calls = append(m.calls, feegrantKeeperCall{ -// expected: req, -// response: response, -// err: err, -// }) -//} -// -//func (m *mockFeegrantKeeper) AllowancesByGranter(ctx context.Context, req *feegrant.QueryAllowancesByGranterRequest) (*feegrant.QueryAllowancesByGranterResponse, error) { -// if m.idx >= len(m.calls) { -// m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - only expected %d calls", m.idx) -// } -// -// call := m.calls[m.idx] -// if !reflect.DeepEqual(req, call.expected) { -// m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - expected: %v, got: %v", call.expected, req) -// } -// -// m.idx++ -// return call.response, call.err -//} -// -//type mockMsg struct{} -// -//func (m *mockMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{} } -//func (m *mockMsg) ValidateBasic() error { return nil } -//func (m *mockMsg) ProtoMessage() {} -//func (m *mockMsg) Reset() {} -//func (m *mockMsg) String() string { return "foo" } -// -//func Test_VerifyAuthorisedSignatureDecorator(t *testing.T) { -// for i, tt := range []struct { -// err error -// setup func(*mockFeegrantKeeper) sdk.Tx -// name string -// }{ -// { -// name: "with no msgs in tx", -// setup: func(*mockFeegrantKeeper) sdk.Tx { -// return &tx{} -// }, -// }, -// { -// name: "with msg without metadata", -// setup: func(*mockFeegrantKeeper) sdk.Tx { -// return &tx{ -// msgs: []sdk.Msg{ -// &mockMsg{}, -// }, -// } -// }, -// }, -// { -// name: "with msg signed by creator", -// setup: func(*mockFeegrantKeeper) sdk.Tx { -// valAddr := sdk.AccAddress("foo") -// return &tx{ -// msgs: []sdk.Msg{ -// &types.MsgAddStatusUpdate{ -// Creator: valAddr.String(), -// Status: "bar", -// Level: 0, -// Metadata: vtypes.MsgMetadata{ -// Creator: valAddr.String(), -// Signers: []string{valAddr.String()}, -// }, -// }, -// }, -// } -// }, -// }, -// { -// name: "with msg signed by valid signature", -// setup: func(k *mockFeegrantKeeper) sdk.Tx { -// valAddr := sdk.AccAddress("foo") -// grantee := sdk.AccAddress("bar") -// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, -// &feegrant.QueryAllowancesByGranterResponse{ -// Allowances: []*feegrant.Grant{ -// { -// Granter: valAddr.String(), -// Grantee: grantee.String(), -// }, -// }, -// }, -// nil) -// return &tx{ -// msgs: []sdk.Msg{ -// &types.MsgAddStatusUpdate{ -// Creator: valAddr.String(), -// Status: "bar", -// Level: 0, -// Metadata: vtypes.MsgMetadata{ -// Creator: valAddr.String(), -// Signers: []string{grantee.String()}, -// }, -// }, -// }, -// } -// }, -// }, -// { -// name: "with msg signed by multiple valid signatures", -// setup: func(k *mockFeegrantKeeper) sdk.Tx { -// valAddr := sdk.AccAddress("foo") -// grantee := sdk.AccAddress("bar") -// grantee2 := sdk.AccAddress("bar") -// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, -// &feegrant.QueryAllowancesByGranterResponse{ -// Allowances: []*feegrant.Grant{ -// { -// Granter: valAddr.String(), -// Grantee: grantee.String(), -// }, -// { -// Granter: valAddr.String(), -// Grantee: grantee2.String(), -// }, -// }, -// }, -// nil) -// return &tx{ -// msgs: []sdk.Msg{ -// &types.MsgAddStatusUpdate{ -// Creator: valAddr.String(), -// Status: "bar", -// Level: 0, -// Metadata: vtypes.MsgMetadata{ -// Creator: valAddr.String(), -// Signers: []string{grantee.String(), grantee2.String()}, -// }, -// }, -// }, -// } -// }, -// }, -// { -// name: "with msg signed by multiple signatures, including at least one valid signature", -// setup: func(k *mockFeegrantKeeper) sdk.Tx { -// valAddr := sdk.AccAddress("foo") -// grantee := sdk.AccAddress("bar") -// grantee2 := sdk.AccAddress("bar") -// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, -// &feegrant.QueryAllowancesByGranterResponse{ -// Allowances: []*feegrant.Grant{ -// { -// Granter: valAddr.String(), -// Grantee: grantee.String(), -// }, -// }, -// }, -// nil) -// return &tx{ -// msgs: []sdk.Msg{ -// &types.MsgAddStatusUpdate{ -// Creator: valAddr.String(), -// Status: "bar", -// Level: 0, -// Metadata: vtypes.MsgMetadata{ -// Creator: valAddr.String(), -// Signers: []string{grantee.String(), grantee2.String()}, -// }, -// }, -// }, -// } -// }, -// }, -// { -// name: "with msg signed by multiple signatures without at least one valid signature", -// err: fmt.Errorf("no signature from granted address found for message"), -// setup: func(k *mockFeegrantKeeper) sdk.Tx { -// valAddr := sdk.AccAddress("foo") -// grantee := sdk.AccAddress("bar") -// grantee2 := sdk.AccAddress("bar") -// k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, -// &feegrant.QueryAllowancesByGranterResponse{ -// Allowances: []*feegrant.Grant{}, -// }, -// nil) -// return &tx{ -// msgs: []sdk.Msg{ -// &types.MsgAddStatusUpdate{ -// Creator: valAddr.String(), -// Status: "bar", -// Level: 0, -// Metadata: vtypes.MsgMetadata{ -// Creator: valAddr.String(), -// Signers: []string{grantee.String(), grantee2.String()}, -// }, -// }, -// }, -// } -// }, -// }, -// } { -// t.Run(fmt.Sprintf("%d. %s", i, tt.name), func(t *testing.T) { -// r := require.New(t) -// k := &mockFeegrantKeeper{t: t} -// tx := tt.setup(k) -// testee := paloma.NewVerifyAuthorisedSignatureDecorator(k) -// ctx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) -// _, err := testee.AnteHandle(ctx, tx, false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { return ctx, nil }) -// -// if tt.err != nil { -// r.ErrorContains(err, tt.err.Error()) -// } else { -// r.NoError(err) -// } -// r.Len(k.calls, k.idx, "unexpected amount of calls") -// }) -// } -//} +import ( + "context" + "fmt" + "reflect" + "testing" + + "cosmossdk.io/x/feegrant" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/palomachain/paloma/x/paloma" + "github.com/palomachain/paloma/x/paloma/types" + vtypes "github.com/palomachain/paloma/x/valset/types" + "github.com/stretchr/testify/require" +) + +type tx struct { + msgs []sdk.Msg +} + +func (t *tx) GetMsgs() []sdk.Msg { + return t.msgs +} + +func (t *tx) ValidateBasic() error { + return nil +} + +type feegrantKeeperCall struct { + expected *feegrant.QueryAllowancesByGranterRequest + response *feegrant.QueryAllowancesByGranterResponse + err error +} +type mockFeegrantKeeper struct { + t *testing.T + calls []feegrantKeeperCall + idx int +} + +func (m *mockFeegrantKeeper) addCall(req *feegrant.QueryAllowancesByGranterRequest, response *feegrant.QueryAllowancesByGranterResponse, err error) { + if m.calls == nil { + m.calls = make([]feegrantKeeperCall, 0) + } + + m.calls = append(m.calls, feegrantKeeperCall{ + expected: req, + response: response, + err: err, + }) +} + +func (m *mockFeegrantKeeper) AllowancesByGranter(ctx context.Context, req *feegrant.QueryAllowancesByGranterRequest) (*feegrant.QueryAllowancesByGranterResponse, error) { + if m.idx >= len(m.calls) { + m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - only expected %d calls", m.idx) + } + + call := m.calls[m.idx] + if !reflect.DeepEqual(req, call.expected) { + m.t.Fatalf("FAIL - FeegrantKeeper.AllowancesByGranter - expected: %v, got: %v", call.expected, req) + } + + m.idx++ + return call.response, call.err +} + +type mockMsg struct{} + +func (m *mockMsg) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{} } +func (m *mockMsg) ValidateBasic() error { return nil } +func (m *mockMsg) ProtoMessage() {} +func (m *mockMsg) Reset() {} +func (m *mockMsg) String() string { return "foo" } + +func Test_VerifyAuthorisedSignatureDecorator(t *testing.T) { + for i, tt := range []struct { + err error + setup func(*mockFeegrantKeeper) sdk.Tx + name string + }{ + { + name: "with no msgs in tx", + setup: func(*mockFeegrantKeeper) sdk.Tx { + return &tx{} + }, + }, + { + name: "with msg without metadata", + setup: func(*mockFeegrantKeeper) sdk.Tx { + return &tx{ + msgs: []sdk.Msg{ + &mockMsg{}, + }, + } + }, + }, + { + name: "with msg signed by creator", + setup: func(*mockFeegrantKeeper) sdk.Tx { + valAddr := sdk.AccAddress("foo") + return &tx{ + msgs: []sdk.Msg{ + &types.MsgAddStatusUpdate{ + Creator: valAddr.String(), + Status: "bar", + Level: 0, + Metadata: vtypes.MsgMetadata{ + Creator: valAddr.String(), + Signers: []string{valAddr.String()}, + }, + }, + }, + } + }, + }, + { + name: "with msg signed by valid signature", + setup: func(k *mockFeegrantKeeper) sdk.Tx { + valAddr := sdk.AccAddress("foo") + grantee := sdk.AccAddress("bar") + k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, + &feegrant.QueryAllowancesByGranterResponse{ + Allowances: []*feegrant.Grant{ + { + Granter: valAddr.String(), + Grantee: grantee.String(), + }, + }, + }, + nil) + return &tx{ + msgs: []sdk.Msg{ + &types.MsgAddStatusUpdate{ + Creator: valAddr.String(), + Status: "bar", + Level: 0, + Metadata: vtypes.MsgMetadata{ + Creator: valAddr.String(), + Signers: []string{grantee.String()}, + }, + }, + }, + } + }, + }, + { + name: "with msg signed by multiple valid signatures", + setup: func(k *mockFeegrantKeeper) sdk.Tx { + valAddr := sdk.AccAddress("foo") + grantee := sdk.AccAddress("bar") + grantee2 := sdk.AccAddress("bar") + k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, + &feegrant.QueryAllowancesByGranterResponse{ + Allowances: []*feegrant.Grant{ + { + Granter: valAddr.String(), + Grantee: grantee.String(), + }, + { + Granter: valAddr.String(), + Grantee: grantee2.String(), + }, + }, + }, + nil) + return &tx{ + msgs: []sdk.Msg{ + &types.MsgAddStatusUpdate{ + Creator: valAddr.String(), + Status: "bar", + Level: 0, + Metadata: vtypes.MsgMetadata{ + Creator: valAddr.String(), + Signers: []string{grantee.String(), grantee2.String()}, + }, + }, + }, + } + }, + }, + { + name: "with msg signed by multiple signatures, including at least one valid signature", + setup: func(k *mockFeegrantKeeper) sdk.Tx { + valAddr := sdk.AccAddress("foo") + grantee := sdk.AccAddress("bar") + grantee2 := sdk.AccAddress("bar") + k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, + &feegrant.QueryAllowancesByGranterResponse{ + Allowances: []*feegrant.Grant{ + { + Granter: valAddr.String(), + Grantee: grantee.String(), + }, + }, + }, + nil) + return &tx{ + msgs: []sdk.Msg{ + &types.MsgAddStatusUpdate{ + Creator: valAddr.String(), + Status: "bar", + Level: 0, + Metadata: vtypes.MsgMetadata{ + Creator: valAddr.String(), + Signers: []string{grantee.String(), grantee2.String()}, + }, + }, + }, + } + }, + }, + { + name: "with msg signed by multiple signatures without at least one valid signature", + err: fmt.Errorf("no signature from granted address found for message"), + setup: func(k *mockFeegrantKeeper) sdk.Tx { + valAddr := sdk.AccAddress("foo") + grantee := sdk.AccAddress("bar") + grantee2 := sdk.AccAddress("bar") + k.addCall(&feegrant.QueryAllowancesByGranterRequest{Granter: valAddr.String()}, + &feegrant.QueryAllowancesByGranterResponse{ + Allowances: []*feegrant.Grant{}, + }, + nil) + return &tx{ + msgs: []sdk.Msg{ + &types.MsgAddStatusUpdate{ + Creator: valAddr.String(), + Status: "bar", + Level: 0, + Metadata: vtypes.MsgMetadata{ + Creator: valAddr.String(), + Signers: []string{grantee.String(), grantee2.String()}, + }, + }, + }, + } + }, + }, + } { + t.Run(fmt.Sprintf("%d. %s", i, tt.name), func(t *testing.T) { + r := require.New(t) + k := &mockFeegrantKeeper{t: t} + tx := tt.setup(k) + testee := paloma.NewVerifyAuthorisedSignatureDecorator(k) + ctx := sdk.NewContext(nil, tmproto.Header{}, false, log.NewNopLogger()) + _, err := testee.AnteHandle(ctx, tx, false, func(ctx sdk.Context, tx sdk.Tx, simulate bool) (sdk.Context, error) { return ctx, nil }) + + if tt.err != nil { + r.ErrorContains(err, tt.err.Error()) + } else { + r.NoError(err) + } + r.Len(k.calls, k.idx, "unexpected amount of calls") + }) + } +} diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index e7903a82..3cad348e 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -86,7 +86,8 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) for _, val := range vals { valAddr, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) + g.Add(err) + continue } exts, err := k.Valset.GetValidatorChainInfos(ctx, valAddr) if err != nil { diff --git a/x/paloma/keeper/keeper_integration_test.go b/x/paloma/keeper/keeper_integration_test.go index c63847c8..57426528 100644 --- a/x/paloma/keeper/keeper_integration_test.go +++ b/x/paloma/keeper/keeper_integration_test.go @@ -55,9 +55,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() // val[2] doesn't have anything // All other vals have everything valAddress, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[0].GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -74,9 +72,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() }) Expect(err).To(BeNil()) valAddress2, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[1].GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress2, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -88,9 +84,7 @@ var _ = Describe("jailing validators with missing external chain infos", func() Expect(err).To(BeNil()) for i, v := range vals[3:] { valAddress, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, v.GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) err = a.ValsetKeeper.AddExternalChainInfo(ctx, valAddress, []*valsettypes.ExternalChainInfo{ { ChainType: "evm", @@ -119,17 +113,11 @@ var _ = Describe("jailing validators with missing external chain infos", func() It("jails val[1] and val[2], but no val[0]", func() { By("validators are not jailed") valAddress1, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[0].GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) valAddress2, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[1].GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) valAddress3, err := utilkeeper.ValAddressFromBech32(k.AddressCodec, vals[2].GetOperator()) - if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) - } + Expect(err).To(BeNil()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress1)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress2)).To(BeFalse()) Expect(a.ValsetKeeper.IsJailed(ctx, valAddress3)).To(BeFalse()) From f0b2a0339f982bf483cd4f48551976f53a20a434 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Mon, 8 Jan 2024 10:52:51 +0530 Subject: [PATCH 15/18] chore: added error from valAddr to whoops --- x/paloma/keeper/keeper.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 3cad348e..2f1999ee 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -112,7 +112,8 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) valAddr, err = utilkeeper.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) if err != nil { - k.Logger(ctx).Error("Error while getting ValAddress", err) + g.Add(err) + continue } if len(notSupported) > 0 { g.Add(k.Valset.Jail(ctx, valAddr, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) From f3246c665bf72bdf26dcf48a33923c2ba5235d89 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Mon, 8 Jan 2024 12:36:51 +0530 Subject: [PATCH 16/18] chore: added test coverage for address.go util --- util/keeper/address_test.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 util/keeper/address_test.go diff --git a/util/keeper/address_test.go b/util/keeper/address_test.go new file mode 100644 index 00000000..659c472b --- /dev/null +++ b/util/keeper/address_test.go @@ -0,0 +1,20 @@ +package keeper + +import ( + "github.com/cosmos/cosmos-sdk/codec/address" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/palomachain/paloma/testutil" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestValAddressConversion(t *testing.T) { + codec := address.Bech32Codec{ + Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), + } + + validators := testutil.GenValidators(1, 25000) + bech32, err := ValAddressFromBech32(codec, validators[0].GetOperator()) + assert.NoError(t, err) + assert.NotNil(t, bech32) +} From ed6900846d875e265cdf6e5e61161a1992958334 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Mon, 8 Jan 2024 18:38:54 +0530 Subject: [PATCH 17/18] chore: removed additional valAddr and added test case --- util/keeper/address_test.go | 6 +++++- x/paloma/keeper/keeper.go | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/util/keeper/address_test.go b/util/keeper/address_test.go index 659c472b..1af5f031 100644 --- a/util/keeper/address_test.go +++ b/util/keeper/address_test.go @@ -13,8 +13,12 @@ func TestValAddressConversion(t *testing.T) { Bech32Prefix: sdk.GetConfig().GetBech32ValidatorAddrPrefix(), } - validators := testutil.GenValidators(1, 25000) + validators := testutil.GenValidators(2, 25000) bech32, err := ValAddressFromBech32(codec, validators[0].GetOperator()) + actual, _ := codec.StringToBytes(validators[0].GetOperator()) + different, _ := ValAddressFromBech32(codec, validators[1].GetOperator()) assert.NoError(t, err) assert.NotNil(t, bech32) + assert.Equal(t, bech32, actual) + assert.NotEqual(t, bech32, different) } diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 2f1999ee..9748a3c1 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -110,7 +110,6 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) sort.Strings(notSupported) - valAddr, err = utilkeeper.ValAddressFromBech32(k.AddressCodec, val.GetOperator()) if err != nil { g.Add(err) continue From 577d88145d48f7ea305a678fa97ef87d08ea4a33 Mon Sep 17 00:00:00 2001 From: deepan95dev Date: Tue, 9 Jan 2024 16:30:59 +0530 Subject: [PATCH 18/18] chore: removed superfluous error check --- x/paloma/keeper/keeper.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/x/paloma/keeper/keeper.go b/x/paloma/keeper/keeper.go index 9748a3c1..ac084f7d 100644 --- a/x/paloma/keeper/keeper.go +++ b/x/paloma/keeper/keeper.go @@ -103,17 +103,11 @@ func (k Keeper) JailValidatorsWithMissingExternalChainInfos(ctx context.Context) notSupported := []string{} for mustExistKey := range mmap { if _, ok := valmap[mustExistKey]; !ok { - // well well well notSupported = append(notSupported, fmt.Sprintf("[%s, %s]", mustExistKey[0], mustExistKey[1])) } } sort.Strings(notSupported) - - if err != nil { - g.Add(err) - continue - } if len(notSupported) > 0 { g.Add(k.Valset.Jail(ctx, valAddr, fmt.Sprintf(types.JailReasonNotSupportingTheseExternalChains, strings.Join(notSupported, ", ")))) }