Upgrade to cosmos-sdk v0.45.0 (#717)

* Upgrade to cosmos-sdk v0.44.5

* Upgrade to sdk v0.45.0-rc1

* Fix local test deploy scripts

* Bump to v0.45.0 final release

* Fixed replace to 0.45.0 not rc1

* Fix changed import path since rc1

Co-authored-by: Ethan Frey <ethanfrey@users.noreply.github.com>
This commit is contained in:
Alexander Peters 2022-01-20 12:47:01 +01:00 committed by GitHub
parent 52477ead36
commit b8319aa334
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
134 changed files with 4249 additions and 4559 deletions

View File

@ -62,7 +62,7 @@ jobs:
lint:
docker:
- image: golangci/golangci-lint:v1.42.1-alpine
- image: golangci/golangci-lint:v1.43.0
steps:
- checkout
- run:

View File

@ -2,47 +2,66 @@ package app
import (
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/cosmos/cosmos-sdk/x/auth/ante"
"github.com/cosmos/cosmos-sdk/x/auth/signing"
"github.com/cosmos/cosmos-sdk/x/auth/types"
channelkeeper "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/keeper"
ibcante "github.com/cosmos/cosmos-sdk/x/ibc/core/ante"
wasmTypes "github.com/CosmWasm/wasmd/x/wasm/types"
channelkeeper "github.com/cosmos/ibc-go/v2/modules/core/04-channel/keeper"
ibcante "github.com/cosmos/ibc-go/v2/modules/core/ante"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
wasmTypes "github.com/CosmWasm/wasmd/x/wasm/types"
)
// NewAnteHandler returns an AnteHandler that checks and increments sequence
// numbers, checks signatures & account numbers, and deducts fees from the first
// signer.
func NewAnteHandler(
ak ante.AccountKeeper,
bankKeeper types.BankKeeper,
sigGasConsumer ante.SignatureVerificationGasConsumer,
signModeHandler signing.SignModeHandler,
txCounterStoreKey sdk.StoreKey,
channelKeeper channelkeeper.Keeper,
wasmConfig wasmTypes.WasmConfig,
) sdk.AnteHandler {
// copied sdk https://github.com/cosmos/cosmos-sdk/blob/v0.42.9/x/auth/ante/ante.go
return sdk.ChainAnteDecorators(
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
wasmkeeper.NewLimitSimulationGasDecorator(wasmConfig.SimulationGasLimit), // after setup context to enforce limits early
wasmkeeper.NewCountTXDecorator(txCounterStoreKey),
// HandlerOptions extend the SDK's AnteHandler options by requiring the IBC
// channel keeper.
type HandlerOptions struct {
ante.HandlerOptions
IBCChannelkeeper channelkeeper.Keeper
WasmConfig *wasmTypes.WasmConfig
TXCounterStoreKey sdk.StoreKey
}
func NewAnteHandler(options HandlerOptions) (sdk.AnteHandler, error) {
if options.AccountKeeper == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "account keeper is required for AnteHandler")
}
if options.BankKeeper == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "bank keeper is required for AnteHandler")
}
if options.SignModeHandler == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "sign mode handler is required for ante builder")
}
if options.WasmConfig == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "wasm config is required for ante builder")
}
if options.TXCounterStoreKey == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrLogic, "tx counter key is required for ante builder")
}
var sigGasConsumer = options.SigGasConsumer
if sigGasConsumer == nil {
sigGasConsumer = ante.DefaultSigVerificationGasConsumer
}
anteDecorators := []sdk.AnteDecorator{
ante.NewSetUpContextDecorator(), // outermost AnteDecorator. SetUpContext must be called first
wasmkeeper.NewLimitSimulationGasDecorator(options.WasmConfig.SimulationGasLimit), // after setup context to enforce limits early
wasmkeeper.NewCountTXDecorator(options.TXCounterStoreKey),
ante.NewRejectExtensionOptionsDecorator(),
ante.NewMempoolFeeDecorator(),
ante.NewValidateBasicDecorator(),
ante.TxTimeoutHeightDecorator{},
ante.NewValidateMemoDecorator(ak),
ante.NewConsumeGasForTxSizeDecorator(ak),
ante.NewRejectFeeGranterDecorator(),
ante.NewSetPubKeyDecorator(ak), // SetPubKeyDecorator must be called before all signature verification decorators
ante.NewValidateSigCountDecorator(ak),
ante.NewDeductFeeDecorator(ak, bankKeeper),
ante.NewSigGasConsumeDecorator(ak, sigGasConsumer),
ante.NewSigVerificationDecorator(ak, signModeHandler),
ante.NewIncrementSequenceDecorator(ak),
ibcante.NewAnteDecorator(channelKeeper),
)
ante.NewTxTimeoutHeightDecorator(),
ante.NewValidateMemoDecorator(options.AccountKeeper),
ante.NewConsumeGasForTxSizeDecorator(options.AccountKeeper),
ante.NewDeductFeeDecorator(options.AccountKeeper, options.BankKeeper, options.FeegrantKeeper),
// SetPubKeyDecorator must be called before all signature verification decorators
ante.NewSetPubKeyDecorator(options.AccountKeeper),
ante.NewValidateSigCountDecorator(options.AccountKeeper),
ante.NewSigGasConsumeDecorator(options.AccountKeeper, sigGasConsumer),
ante.NewSigVerificationDecorator(options.AccountKeeper, options.SignModeHandler),
ante.NewIncrementSequenceDecorator(options.AccountKeeper),
ibcante.NewAnteDecorator(options.IBCChannelkeeper),
}
return sdk.ChainAnteDecorators(anteDecorators...), nil
}

View File

@ -8,19 +8,9 @@ import (
"path/filepath"
"strings"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cast"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/grpc/tmservice"
"github.com/cosmos/cosmos-sdk/client/rpc"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
@ -39,6 +29,10 @@ import (
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/cosmos/cosmos-sdk/x/auth/vesting"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/cosmos/cosmos-sdk/x/authz"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
authzmodule "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/bank"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
@ -55,19 +49,14 @@ import (
"github.com/cosmos/cosmos-sdk/x/evidence"
evidencekeeper "github.com/cosmos/cosmos-sdk/x/evidence/keeper"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/feegrant"
feegrantkeeper "github.com/cosmos/cosmos-sdk/x/feegrant/keeper"
feegrantmodule "github.com/cosmos/cosmos-sdk/x/feegrant/module"
"github.com/cosmos/cosmos-sdk/x/genutil"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/cosmos/cosmos-sdk/x/gov"
govkeeper "github.com/cosmos/cosmos-sdk/x/gov/keeper"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
transfer "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer"
ibctransferkeeper "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/keeper"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
ibc "github.com/cosmos/cosmos-sdk/x/ibc/core"
ibcclient "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client"
porttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/05-port/types"
ibchost "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
ibckeeper "github.com/cosmos/cosmos-sdk/x/ibc/core/keeper"
"github.com/cosmos/cosmos-sdk/x/mint"
mintkeeper "github.com/cosmos/cosmos-sdk/x/mint/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
@ -86,7 +75,27 @@ 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"
transfer "github.com/cosmos/ibc-go/v2/modules/apps/transfer"
ibctransferkeeper "github.com/cosmos/ibc-go/v2/modules/apps/transfer/keeper"
ibctransfertypes "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types"
ibc "github.com/cosmos/ibc-go/v2/modules/core"
ibcclient "github.com/cosmos/ibc-go/v2/modules/core/02-client"
ibcclientclient "github.com/cosmos/ibc-go/v2/modules/core/02-client/client"
ibcclienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
porttypes "github.com/cosmos/ibc-go/v2/modules/core/05-port/types"
ibchost "github.com/cosmos/ibc-go/v2/modules/core/24-host"
ibckeeper "github.com/cosmos/ibc-go/v2/modules/core/keeper"
"github.com/gorilla/mux"
"github.com/rakyll/statik/fs"
"github.com/spf13/cast"
abci "github.com/tendermint/tendermint/abci/types"
tmjson "github.com/tendermint/tendermint/libs/json"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
wasmappparams "github.com/CosmWasm/wasmd/app/params"
"github.com/CosmWasm/wasmd/x/wasm"
wasmclient "github.com/CosmWasm/wasmd/x/wasm/client"
@ -161,17 +170,27 @@ var (
mint.AppModuleBasic{},
distr.AppModuleBasic{},
gov.NewAppModuleBasic(
append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler)...,
append(
wasmclient.ProposalHandlers,
paramsclient.ProposalHandler,
distrclient.ProposalHandler,
upgradeclient.ProposalHandler,
upgradeclient.CancelProposalHandler,
ibcclientclient.UpdateClientProposalHandler,
ibcclientclient.UpgradeProposalHandler,
)...,
),
params.AppModuleBasic{},
wasm.AppModuleBasic{},
crisis.AppModuleBasic{},
slashing.AppModuleBasic{},
feegrantmodule.AppModuleBasic{},
authzmodule.AppModuleBasic{},
ibc.AppModuleBasic{},
upgrade.AppModuleBasic{},
evidence.AppModuleBasic{},
transfer.AppModuleBasic{},
vesting.AppModuleBasic{},
wasm.AppModuleBasic{},
)
// module account permissions
@ -187,7 +206,6 @@ var (
}
)
// Verify app interface at compile time
var (
_ simapp.App = (*WasmApp)(nil)
_ servertypes.Application = (*WasmApp)(nil)
@ -197,7 +215,7 @@ var (
type WasmApp struct {
*baseapp.BaseApp
legacyAmino *codec.LegacyAmino //nolint:staticcheck
appCodec codec.Marshaler
appCodec codec.Codec
interfaceRegistry types.InterfaceRegistry
invCheckPeriod uint
@ -222,6 +240,8 @@ type WasmApp struct {
ibcKeeper *ibckeeper.Keeper // IBC Keeper must be a pointer in the app, so we can SetRouter on it correctly
evidenceKeeper evidencekeeper.Keeper
transferKeeper ibctransferkeeper.Keeper
FeeGrantKeeper feegrantkeeper.Keeper
AuthzKeeper authzkeeper.Keeper
wasmKeeper wasm.Keeper
scopedIBCKeeper capabilitykeeper.ScopedKeeper
@ -233,6 +253,9 @@ type WasmApp struct {
// simulation manager
sm *module.SimulationManager
// module configurator
configurator module.Configurator
}
// NewWasmApp returns a reference to an initialized WasmApp.
@ -244,19 +267,19 @@ func NewWasmApp(
skipUpgradeHeights map[int64]bool,
homePath string,
invCheckPeriod uint,
encodingConfig wasmappparams.EncodingConfig,
enabledProposals []wasm.ProposalType,
appOpts servertypes.AppOptions,
wasmOpts []wasm.Option,
baseAppOptions ...func(*baseapp.BaseApp),
) *WasmApp {
encodingConfig := MakeEncodingConfig()
appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino
interfaceRegistry := encodingConfig.InterfaceRegistry
bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...)
bApp.SetCommitMultiStoreTracer(traceStore)
bApp.SetAppVersion(version.Version)
bApp.SetVersion(version.Version)
bApp.SetInterfaceRegistry(interfaceRegistry)
keys := sdk.NewKVStoreKeys(
@ -264,7 +287,7 @@ func NewWasmApp(
minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey,
govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey,
evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey,
wasm.StoreKey,
feegrant.StoreKey, authzkeeper.StoreKey, wasm.StoreKey,
)
tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey)
memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey)
@ -280,42 +303,97 @@ func NewWasmApp(
memKeys: memKeys,
}
app.paramsKeeper = initParamsKeeper(appCodec, legacyAmino, keys[paramstypes.StoreKey], tkeys[paramstypes.TStoreKey])
app.paramsKeeper = initParamsKeeper(
appCodec,
legacyAmino,
keys[paramstypes.StoreKey],
tkeys[paramstypes.TStoreKey],
)
// set the BaseApp's parameter store
bApp.SetParamStore(app.paramsKeeper.Subspace(baseapp.Paramspace).WithKeyTable(paramskeeper.ConsensusParamsKeyTable()))
// add capability keeper and ScopeToModule for ibc module
app.capabilityKeeper = capabilitykeeper.NewKeeper(appCodec, keys[capabilitytypes.StoreKey], memKeys[capabilitytypes.MemStoreKey])
app.capabilityKeeper = capabilitykeeper.NewKeeper(
appCodec,
keys[capabilitytypes.StoreKey],
memKeys[capabilitytypes.MemStoreKey],
)
scopedIBCKeeper := app.capabilityKeeper.ScopeToModule(ibchost.ModuleName)
scopedTransferKeeper := app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName)
scopedWasmKeeper := app.capabilityKeeper.ScopeToModule(wasm.ModuleName)
app.capabilityKeeper.Seal()
// add keepers
app.accountKeeper = authkeeper.NewAccountKeeper(
appCodec, keys[authtypes.StoreKey], app.getSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms,
appCodec,
keys[authtypes.StoreKey],
app.getSubspace(authtypes.ModuleName),
authtypes.ProtoBaseAccount,
maccPerms,
)
app.bankKeeper = bankkeeper.NewBaseKeeper(
appCodec, keys[banktypes.StoreKey], app.accountKeeper, app.getSubspace(banktypes.ModuleName), app.ModuleAccountAddrs(),
appCodec,
keys[banktypes.StoreKey],
app.accountKeeper,
app.getSubspace(banktypes.ModuleName),
app.ModuleAccountAddrs(),
)
app.AuthzKeeper = authzkeeper.NewKeeper(
keys[authzkeeper.StoreKey],
appCodec,
app.BaseApp.MsgServiceRouter(),
)
app.FeeGrantKeeper = feegrantkeeper.NewKeeper(
appCodec,
keys[feegrant.StoreKey],
app.accountKeeper,
)
stakingKeeper := stakingkeeper.NewKeeper(
appCodec, keys[stakingtypes.StoreKey], app.accountKeeper, app.bankKeeper, app.getSubspace(stakingtypes.ModuleName),
appCodec,
keys[stakingtypes.StoreKey],
app.accountKeeper,
app.bankKeeper,
app.getSubspace(stakingtypes.ModuleName),
)
app.mintKeeper = mintkeeper.NewKeeper(
appCodec, keys[minttypes.StoreKey], app.getSubspace(minttypes.ModuleName), &stakingKeeper,
app.accountKeeper, app.bankKeeper, authtypes.FeeCollectorName,
appCodec,
keys[minttypes.StoreKey],
app.getSubspace(minttypes.ModuleName),
&stakingKeeper,
app.accountKeeper,
app.bankKeeper,
authtypes.FeeCollectorName,
)
app.distrKeeper = distrkeeper.NewKeeper(
appCodec, keys[distrtypes.StoreKey], app.getSubspace(distrtypes.ModuleName), app.accountKeeper, app.bankKeeper,
&stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(),
appCodec,
keys[distrtypes.StoreKey],
app.getSubspace(distrtypes.ModuleName),
app.accountKeeper,
app.bankKeeper,
&stakingKeeper,
authtypes.FeeCollectorName,
app.ModuleAccountAddrs(),
)
app.slashingKeeper = slashingkeeper.NewKeeper(
appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.getSubspace(slashingtypes.ModuleName),
appCodec,
keys[slashingtypes.StoreKey],
&stakingKeeper,
app.getSubspace(slashingtypes.ModuleName),
)
app.crisisKeeper = crisiskeeper.NewKeeper(
app.getSubspace(crisistypes.ModuleName), invCheckPeriod, app.bankKeeper, authtypes.FeeCollectorName,
app.getSubspace(crisistypes.ModuleName),
invCheckPeriod,
app.bankKeeper,
authtypes.FeeCollectorName,
)
app.upgradeKeeper = upgradekeeper.NewKeeper(
skipUpgradeHeights,
keys[upgradetypes.StoreKey],
appCodec,
homePath,
app.BaseApp,
)
app.upgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath)
// register the staking hooks
// NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks
@ -323,34 +401,47 @@ func NewWasmApp(
stakingtypes.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()),
)
// Create IBC Keeper
app.ibcKeeper = ibckeeper.NewKeeper(
appCodec, keys[ibchost.StoreKey], app.getSubspace(ibchost.ModuleName), app.stakingKeeper, scopedIBCKeeper,
appCodec,
keys[ibchost.StoreKey],
app.getSubspace(ibchost.ModuleName),
app.stakingKeeper,
app.upgradeKeeper,
scopedIBCKeeper,
)
// register the proposal types
govRouter := govtypes.NewRouter()
govRouter.AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
govRouter.
AddRoute(govtypes.RouterKey, govtypes.ProposalHandler).
AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)).
AddRoute(distrtypes.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)).
AddRoute(upgradetypes.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)).
AddRoute(ibchost.RouterKey, ibcclient.NewClientUpdateProposalHandler(app.ibcKeeper.ClientKeeper))
AddRoute(ibcclienttypes.RouterKey, ibcclient.NewClientProposalHandler(app.ibcKeeper.ClientKeeper))
// Create Transfer Keepers
app.transferKeeper = ibctransferkeeper.NewKeeper(
appCodec, keys[ibctransfertypes.StoreKey], app.getSubspace(ibctransfertypes.ModuleName),
app.ibcKeeper.ChannelKeeper, &app.ibcKeeper.PortKeeper,
app.accountKeeper, app.bankKeeper, scopedTransferKeeper,
appCodec,
keys[ibctransfertypes.StoreKey],
app.getSubspace(ibctransfertypes.ModuleName),
app.ibcKeeper.ChannelKeeper,
&app.ibcKeeper.PortKeeper,
app.accountKeeper,
app.bankKeeper,
scopedTransferKeeper,
)
transferModule := transfer.NewAppModule(app.transferKeeper)
// Create static IBC router, add transfer route, then set and seal it
// create static IBC router, add transfer route, then set and seal it
ibcRouter := porttypes.NewRouter()
ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferModule)
// create evidence keeper with router
evidenceKeeper := evidencekeeper.NewKeeper(
appCodec, keys[evidencetypes.StoreKey], &app.stakingKeeper, app.slashingKeeper,
appCodec,
keys[evidencetypes.StoreKey],
&app.stakingKeeper,
app.slashingKeeper,
)
app.evidenceKeeper = *evidenceKeeper
@ -375,7 +466,7 @@ func NewWasmApp(
&app.ibcKeeper.PortKeeper,
scopedWasmKeeper,
app.transferKeeper,
app.Router(),
app.MsgServiceRouter(),
app.GRPCQueryRouter(),
wasmDir,
wasmConfig,
@ -409,14 +500,15 @@ func NewWasmApp(
// must be passed by reference here.
app.mm = module.NewManager(
genutil.NewAppModule(
app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx,
app.accountKeeper,
app.stakingKeeper,
app.BaseApp.DeliverTx,
encodingConfig.TxConfig,
),
auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts),
auth.NewAppModule(appCodec, app.accountKeeper, nil),
vesting.NewAppModule(app.accountKeeper, app.bankKeeper),
bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper),
capability.NewAppModule(appCodec, *app.capabilityKeeper),
crisis.NewAppModule(&app.crisisKeeper, skipGenesisInvariants),
gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper),
mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper),
slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
@ -425,9 +517,12 @@ func NewWasmApp(
upgrade.NewAppModule(app.upgradeKeeper),
wasm.NewAppModule(appCodec, &app.wasmKeeper, app.stakingKeeper),
evidence.NewAppModule(app.evidenceKeeper),
feegrantmodule.NewAppModule(appCodec, app.accountKeeper, app.bankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry),
ibc.NewAppModule(app.ibcKeeper),
params.NewAppModule(app.paramsKeeper),
transferModule,
crisis.NewAppModule(&app.crisisKeeper, skipGenesisInvariants), // always be last to make sure that it checks for all invariants and not only part of them
)
// During begin block slashing happens after distr.BeginBlocker so that
@ -435,32 +530,67 @@ func NewWasmApp(
// CanWithdrawInvariant invariant.
// NOTE: staking module is required if HistoricalEntries param > 0
app.mm.SetOrderBeginBlockers(
upgradetypes.ModuleName, capabilitytypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName,
evidencetypes.ModuleName, stakingtypes.ModuleName, ibchost.ModuleName,
upgradetypes.ModuleName,
capabilitytypes.ModuleName,
minttypes.ModuleName,
distrtypes.ModuleName,
slashingtypes.ModuleName,
evidencetypes.ModuleName,
stakingtypes.ModuleName,
authtypes.ModuleName,
banktypes.ModuleName,
govtypes.ModuleName,
crisistypes.ModuleName,
genutiltypes.ModuleName,
authz.ModuleName,
feegrant.ModuleName,
paramstypes.ModuleName,
vestingtypes.ModuleName,
// additional non simd modules
ibchost.ModuleName,
ibctransfertypes.ModuleName,
wasm.ModuleName,
)
app.mm.SetOrderEndBlockers(crisistypes.ModuleName, govtypes.ModuleName, stakingtypes.ModuleName)
// NOTE: The genutils module must occur after staking so that pools are
// properly initialized with tokens from genesis accounts.
// NOTE: Capability module must occur first so that it can initialize any capabilities
// so that other modules that want to create or claim capabilities afterwards in InitChain
// can do so safely.
// wasm module should be a the end as it can call other modules functionality direct or via message dispatching during
// NOTE: wasm module should be at the end as it can call other module functionality direct or via message dispatching during
// genesis phase. For example bank transfer, auth account check, staking, ...
app.mm.SetOrderInitGenesis(
capabilitytypes.ModuleName, authtypes.ModuleName, banktypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName,
slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName,
ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName,
capabilitytypes.ModuleName,
authtypes.ModuleName,
banktypes.ModuleName,
distrtypes.ModuleName,
stakingtypes.ModuleName,
slashingtypes.ModuleName,
govtypes.ModuleName,
minttypes.ModuleName,
crisistypes.ModuleName,
genutiltypes.ModuleName,
evidencetypes.ModuleName,
authz.ModuleName,
feegrant.ModuleName,
paramstypes.ModuleName,
upgradetypes.ModuleName,
vestingtypes.ModuleName,
// additional non simd modules
ibchost.ModuleName,
ibctransfertypes.ModuleName,
// wasm after ibc transfer
wasm.ModuleName,
)
// Uncomment if you want to set a custom migration order here.
// app.mm.SetOrderMigrations(custom order)
app.mm.RegisterInvariants(&app.crisisKeeper)
app.mm.RegisterRoutes(app.Router(), app.QueryRouter(), encodingConfig.Amino)
app.mm.RegisterServices(module.NewConfigurator(app.MsgServiceRouter(), app.GRPCQueryRouter()))
// add test gRPC service for testing gRPC queries in isolation
// testdata.RegisterTestServiceServer(app.GRPCQueryRouter(), testdata.QueryImpl{}) // TODO: this is testdata !!!!
app.configurator = module.NewConfigurator(app.appCodec, app.MsgServiceRouter(), app.GRPCQueryRouter())
app.mm.RegisterServices(app.configurator)
// create the simulation manager and define the order of the modules for deterministic simulations
//
@ -470,14 +600,16 @@ func NewWasmApp(
auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts),
bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper),
capability.NewAppModule(appCodec, *app.capabilityKeeper),
feegrantmodule.NewAppModule(appCodec, app.accountKeeper, app.bankKeeper, app.FeeGrantKeeper, app.interfaceRegistry),
authzmodule.NewAppModule(appCodec, app.AuthzKeeper, app.accountKeeper, app.bankKeeper, app.interfaceRegistry),
gov.NewAppModule(appCodec, app.govKeeper, app.accountKeeper, app.bankKeeper),
mint.NewAppModule(appCodec, app.mintKeeper, app.accountKeeper),
staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper),
distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
slashing.NewAppModule(appCodec, app.slashingKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper),
params.NewAppModule(app.paramsKeeper),
wasm.NewAppModule(appCodec, &app.wasmKeeper, app.stakingKeeper),
evidence.NewAppModule(app.evidenceKeeper),
wasm.NewAppModule(appCodec, &app.wasmKeeper, app.stakingKeeper),
ibc.NewAppModule(app.ibcKeeper),
transferModule,
)
@ -489,36 +621,38 @@ func NewWasmApp(
app.MountTransientStores(tkeys)
app.MountMemoryStores(memKeys)
// initialize BaseApp
anteHandler, err := NewAnteHandler(
HandlerOptions{
HandlerOptions: ante.HandlerOptions{
AccountKeeper: app.accountKeeper,
BankKeeper: app.bankKeeper,
FeegrantKeeper: app.FeeGrantKeeper,
SignModeHandler: encodingConfig.TxConfig.SignModeHandler(),
SigGasConsumer: ante.DefaultSigVerificationGasConsumer,
},
IBCChannelkeeper: app.ibcKeeper.ChannelKeeper,
WasmConfig: &wasmConfig,
TXCounterStoreKey: keys[wasm.StoreKey],
},
)
if err != nil {
panic(fmt.Errorf("failed to create AnteHandler: %s", err))
}
app.SetAnteHandler(anteHandler)
app.SetInitChainer(app.InitChainer)
app.SetBeginBlocker(app.BeginBlocker)
app.SetAnteHandler(
NewAnteHandler(
app.accountKeeper, app.bankKeeper, ante.DefaultSigVerificationGasConsumer,
encodingConfig.TxConfig.SignModeHandler(), keys[wasm.StoreKey], app.ibcKeeper.ChannelKeeper,
wasmConfig,
),
)
app.SetEndBlocker(app.EndBlocker)
if loadLatest {
if err := app.LoadLatestVersion(); err != nil {
tmos.Exit(err.Error())
tmos.Exit(fmt.Sprintf("failed to load latest version: %s", err))
}
// Initialize and seal the capability keeper so all persistent capabilities
// are loaded in-memory and prevent any further modules from creating scoped
// sub-keepers.
// This must be done during creation of baseapp rather than in InitChain so
// that in-memory capabilities get regenerated on app restart.
// Note that since this reads from the store, we can only perform it when
// `loadLatest` is set to true.
ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{})
app.capabilityKeeper.InitializeAndSeal(ctx)
// Initialize pinned codes in wasmvm as they are not persisted there
if err := app.wasmKeeper.InitializePinnedCodes(ctx); err != nil {
panic(err)
tmos.Exit(fmt.Sprintf("failed initialize pinned codes %s", err))
}
}
@ -547,6 +681,9 @@ func (app *WasmApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci
if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil {
panic(err)
}
app.upgradeKeeper.SetModuleVersionMap(ctx, app.mm.GetVersionMap())
return app.mm.InitGenesis(ctx, app.appCodec, genesisState)
}
@ -565,7 +702,7 @@ func (app *WasmApp) ModuleAccountAddrs() map[string]bool {
return modAccAddrs
}
// LegacyAmino returns SimApp's amino codec.
// LegacyAmino returns legacy amino codec.
//
// NOTE: This is solely to be used for testing purposes as it may be desirable
// for modules to register their own custom testing types.
@ -573,11 +710,6 @@ func (app *WasmApp) LegacyAmino() *codec.LegacyAmino { //nolint:staticcheck
return app.legacyAmino
}
// SimulationManager implements the SimulationApp interface
func (app *WasmApp) SimulationManager() *module.SimulationManager {
return app.sm
}
// getSubspace returns a param subspace for a given module name.
//
// NOTE: This is solely to be used for testing purposes.
@ -586,6 +718,11 @@ func (app *WasmApp) getSubspace(moduleName string) paramstypes.Subspace {
return subspace
}
// SimulationManager implements the SimulationApp interface
func (app *WasmApp) SimulationManager() *module.SimulationManager {
return app.sm
}
// RegisterAPIRoutes registers all application module routes with the provided
// API server.
func (app *WasmApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) {
@ -604,7 +741,7 @@ func (app *WasmApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APICo
// register swagger API from root so that other applications can override easily
if apiConfig.Swagger {
RegisterSwaggerAPI(clientCtx, apiSvr.Router)
RegisterSwaggerAPI(apiSvr.Router)
}
}
@ -618,12 +755,12 @@ func (app *WasmApp) RegisterTendermintService(clientCtx client.Context) {
tmservice.RegisterTendermintService(app.BaseApp.GRPCQueryRouter(), clientCtx, app.interfaceRegistry)
}
func (app *WasmApp) AppCodec() codec.JSONMarshaler {
func (app *WasmApp) AppCodec() codec.Codec {
return app.appCodec
}
// RegisterSwaggerAPI registers swagger route with API Server
func RegisterSwaggerAPI(_ client.Context, rtr *mux.Router) {
func RegisterSwaggerAPI(rtr *mux.Router) {
statikFS, err := fs.New()
if err != nil {
panic(err)
@ -643,7 +780,7 @@ func GetMaccPerms() map[string][]string {
}
// initParamsKeeper init params keeper and its subspaces
func initParamsKeeper(appCodec codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { //nolint:staticcheck
func initParamsKeeper(appCodec codec.BinaryCodec, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper {
paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey)
paramsKeeper.Subspace(authtypes.ModuleName)

View File

@ -19,7 +19,7 @@ var emptyWasmOpts []wasm.Option = nil
func TestWasmdExport(t *testing.T) {
db := db.NewMemDB()
gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
genesisState := NewDefaultGenesisState()
stateBytes, err := json.MarshalIndent(genesisState, "", " ")
@ -35,7 +35,7 @@ func TestWasmdExport(t *testing.T) {
gapp.Commit()
// Making a new app object with the db, so that initchain hasn't been called
newGapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
newGapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
_, err = newGapp.ExportAppStateAndValidators(false, []string{})
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}
@ -43,7 +43,7 @@ func TestWasmdExport(t *testing.T) {
// ensure that blocked addresses are properly set in bank keeper
func TestBlockedAddrs(t *testing.T) {
db := db.NewMemDB()
gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, DefaultNodeHome, 0, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, emptyWasmOpts)
for acc := range maccPerms {
t.Run(acc, func(t *testing.T) {

View File

@ -1,37 +1,17 @@
package app
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/std"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
"github.com/CosmWasm/wasmd/app/params"
)
// EncodingConfig specifies the concrete encoding types to use for a given app.
// This is provided for compatibility between protobuf and amino implementations.
type EncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Marshaler codec.Marshaler
TxConfig client.TxConfig
Amino *codec.LegacyAmino //nolint:staticcheck
}
func MakeEncodingConfig() EncodingConfig {
amino := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := codec.NewProtoCodec(interfaceRegistry)
txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes)
std.RegisterInterfaces(interfaceRegistry)
std.RegisterLegacyAminoCodec(amino)
ModuleBasics.RegisterLegacyAminoCodec(amino)
ModuleBasics.RegisterInterfaces(interfaceRegistry)
return EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: txCfg,
Amino: amino,
}
// MakeEncodingConfig creates a new EncodingConfig with all modules registered
func MakeEncodingConfig() params.EncodingConfig {
encodingConfig := params.MakeEncodingConfig()
std.RegisterLegacyAminoCodec(encodingConfig.Amino)
std.RegisterInterfaces(encodingConfig.InterfaceRegistry)
ModuleBasics.RegisterLegacyAminoCodec(encodingConfig.Amino)
ModuleBasics.RegisterInterfaces(encodingConfig.InterfaceRegistry)
return encodingConfig
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
)
// The genesis state of the blockchain is represented here as a map of raw json
// GenesisState The genesis state of the blockchain is represented here as a map of raw json
// messages key'd by a identifier string.
// The identifier is used to determine which module genesis information belongs
// to so it may be appropriately routed during init chain.
@ -15,6 +15,6 @@ type GenesisState map[string]json.RawMessage
// NewDefaultGenesisState generates the default state for the application.
func NewDefaultGenesisState() GenesisState {
encCfg := MakeEncodingConfig()
return ModuleBasics.DefaultGenesis(encCfg.Marshaler)
encodingConfig := MakeEncodingConfig()
return ModuleBasics.DefaultGenesis(encodingConfig.Marshaler)
}

19
app/params/doc.go Normal file
View File

@ -0,0 +1,19 @@
/*
Package params defines the simulation parameters in the gaia.
It contains the default weights used for each transaction used on the module's
simulation. These weights define the chance for a transaction to be simulated at
any gived operation.
You can repace the default values for the weights by providing a params.json
file with the weights defined for each of the transaction operations:
{
"op_weight_msg_send": 60,
"op_weight_msg_delegate": 100,
}
In the example above, the `MsgSend` has 60% chance to be simulated, while the
`MsgDelegate` will always be simulated.
*/
package params

16
app/params/encoding.go Normal file
View File

@ -0,0 +1,16 @@
package params
import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
)
// EncodingConfig specifies the concrete encoding types to use for a given app.
// This is provided for compatibility between protobuf and amino implementations.
type EncodingConfig struct {
InterfaceRegistry types.InterfaceRegistry
Marshaler codec.Codec
TxConfig client.TxConfig
Amino *codec.LegacyAmino
}

7
app/params/params.go Normal file
View File

@ -0,0 +1,7 @@
package params
// Simulation parameter constants
const (
StakePerAccount = "stake_per_account"
InitiallyBondedValidators = "initially_bonded_validators"
)

22
app/params/proto.go Normal file
View File

@ -0,0 +1,22 @@
package params
import (
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/x/auth/tx"
)
// MakeEncodingConfig creates an EncodingConfig for an amino based test configuration.
func MakeEncodingConfig() EncodingConfig {
amino := codec.NewLegacyAmino()
interfaceRegistry := types.NewInterfaceRegistry()
marshaler := codec.NewProtoCodec(interfaceRegistry)
txCfg := tx.NewTxConfig(marshaler, tx.DefaultSignModes)
return EncodingConfig{
InterfaceRegistry: interfaceRegistry,
Marshaler: marshaler,
TxConfig: txCfg,
Amino: amino,
}
}

23
app/params/weights.go Normal file
View File

@ -0,0 +1,23 @@
package params
// Default simulation operation weights for messages and gov proposals
const (
DefaultWeightMsgSend int = 100
DefaultWeightMsgMultiSend int = 10
DefaultWeightMsgSetWithdrawAddress int = 50
DefaultWeightMsgWithdrawDelegationReward int = 50
DefaultWeightMsgWithdrawValidatorCommission int = 50
DefaultWeightMsgFundCommunityPool int = 50
DefaultWeightMsgDeposit int = 100
DefaultWeightMsgVote int = 67
DefaultWeightMsgUnjail int = 100
DefaultWeightMsgCreateValidator int = 100
DefaultWeightMsgEditValidator int = 5
DefaultWeightMsgDelegate int = 100
DefaultWeightMsgUndelegate int = 100
DefaultWeightMsgBeginRedelegate int = 100
DefaultWeightCommunitySpendProposal int = 5
DefaultWeightTextProposal int = 5
DefaultWeightParamChangeProposal int = 5
)

View File

@ -13,24 +13,27 @@ import (
"github.com/cosmos/cosmos-sdk/types/kv"
simtypes "github.com/cosmos/cosmos-sdk/types/simulation"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
authzkeeper "github.com/cosmos/cosmos-sdk/x/authz/keeper"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
evidencetypes "github.com/cosmos/cosmos-sdk/x/evidence/types"
"github.com/cosmos/cosmos-sdk/x/feegrant"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
ibchost "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
paramstypes "github.com/cosmos/cosmos-sdk/x/params/types"
"github.com/cosmos/cosmos-sdk/x/simulation"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
ibctransfertypes "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types"
ibchost "github.com/cosmos/ibc-go/v2/modules/core/24-host"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/log"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/CosmWasm/wasmd/x/wasm"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
)
// Get flags every time the simulator is run
@ -81,7 +84,7 @@ func GetSimulationLog(storeName string, sdr sdk.StoreDecoderRegistry, kvAs, kvBs
if ok {
log += decoder(kvAs[i], kvBs[i])
} else {
log += fmt.Sprintf("store A %s => %s\nstore B %s => %s\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value)
log += fmt.Sprintf("store A %q => %q\nstore B %q => %q\n", kvAs[i].Key, kvAs[i].Value, kvBs[i].Key, kvBs[i].Value)
}
}
@ -106,7 +109,8 @@ func TestAppImportExport(t *testing.T) {
require.NoError(t, os.RemoveAll(dir))
}()
app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt)
encConf := MakeEncodingConfig()
app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, dir, simapp.FlagPeriodValue, encConf, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt)
require.Equal(t, appName, app.Name())
// Run randomized simulation
@ -131,12 +135,12 @@ func TestAppImportExport(t *testing.T) {
simapp.PrintStats(db)
}
fmt.Printf("exporting genesis...\n")
t.Log("exporting genesis...")
exported, err := app.ExportAppStateAndValidators(false, []string{})
require.NoError(t, err)
fmt.Printf("importing genesis...\n")
t.Log("importing genesis...")
_, newDB, newDir, _, _, err := SetupSimulation("leveldb-app-sim-2", "Simulation-2")
require.NoError(t, err, "simulation setup failed")
@ -145,8 +149,7 @@ func TestAppImportExport(t *testing.T) {
newDB.Close()
require.NoError(t, os.RemoveAll(newDir))
}()
newApp := NewWasmApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt)
newApp := NewWasmApp(logger, newDB, nil, true, map[int64]bool{}, newDir, simapp.FlagPeriodValue, encConf, wasm.EnableAllProposals, EmptyBaseAppOptions{}, nil, fauxMerkleModeOpt)
require.Equal(t, appName, newApp.Name())
var genesisState GenesisState
@ -158,7 +161,7 @@ func TestAppImportExport(t *testing.T) {
newApp.mm.InitGenesis(ctxB, app.AppCodec(), genesisState)
newApp.StoreConsensusParams(ctxB, exported.ConsensusParams)
fmt.Printf("comparing stores...\n")
t.Log("comparing stores...")
storeKeysPrefixes := []StoreKeysPrefixes{
{app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}},
@ -177,9 +180,15 @@ func TestAppImportExport(t *testing.T) {
{app.keys[capabilitytypes.StoreKey], newApp.keys[capabilitytypes.StoreKey], [][]byte{}},
{app.keys[ibchost.StoreKey], newApp.keys[ibchost.StoreKey], [][]byte{}},
{app.keys[ibctransfertypes.StoreKey], newApp.keys[ibctransfertypes.StoreKey], [][]byte{}},
{app.keys[authzkeeper.StoreKey], newApp.keys[authzkeeper.StoreKey], [][]byte{}},
{app.keys[feegrant.StoreKey], newApp.keys[feegrant.StoreKey], [][]byte{}},
{app.keys[wasm.StoreKey], newApp.keys[wasm.StoreKey], [][]byte{}},
}
// delete persistent tx counter value
ctxA.KVStore(app.keys[wasm.StoreKey]).Delete(wasmtypes.TXCounterPrefix)
// diff both stores
for _, skp := range storeKeysPrefixes {
storeA := ctxA.KVStore(skp.A)
storeB := ctxB.KVStore(skp.B)
@ -187,7 +196,7 @@ func TestAppImportExport(t *testing.T) {
failedKVAs, failedKVBs := sdk.DiffKVStores(storeA, storeB, skp.Prefixes)
require.Equal(t, len(failedKVAs), len(failedKVBs), "unequal sets of key-values to compare")
fmt.Printf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B)
t.Logf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B)
require.Len(t, failedKVAs, 0, GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs))
}
}
@ -203,9 +212,9 @@ func TestFullAppSimulation(t *testing.T) {
db.Close()
require.NoError(t, os.RemoveAll(dir))
}()
encConf := MakeEncodingConfig()
app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, DefaultNodeHome, simapp.FlagPeriodValue,
wasm.EnableAllProposals, simapp.EmptyAppOptions{}, nil, fauxMerkleModeOpt)
encConf, wasm.EnableAllProposals, simapp.EmptyAppOptions{}, nil, fauxMerkleModeOpt)
require.Equal(t, "WasmApp", app.Name())
// run randomized simulation

View File

@ -3,34 +3,39 @@ package app
import (
"testing"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/CosmWasm/wasmd/app/params"
"github.com/cosmos/cosmos-sdk/codec"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper"
ibctransferkeeper "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/keeper"
ibckeeper "github.com/cosmos/cosmos-sdk/x/ibc/core/keeper"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
ibctransferkeeper "github.com/cosmos/ibc-go/v2/modules/apps/transfer/keeper"
ibckeeper "github.com/cosmos/ibc-go/v2/modules/core/keeper"
"github.com/CosmWasm/wasmd/x/wasm"
)
type TestSupport struct {
t *testing.T
t testing.TB
app *WasmApp
}
func NewTestSupport(t *testing.T, app *WasmApp) *TestSupport {
func NewTestSupport(t testing.TB, app *WasmApp) *TestSupport {
return &TestSupport{t: t, app: app}
}
func (s TestSupport) IBCKeeper() ibckeeper.Keeper {
return *s.app.ibcKeeper
func (s TestSupport) IBCKeeper() *ibckeeper.Keeper {
return s.app.ibcKeeper
}
func (s TestSupport) WasmKeeper() wasm.Keeper {
return s.app.wasmKeeper
}
func (s TestSupport) AppCodec() codec.Marshaler {
func (s TestSupport) AppCodec() codec.Codec {
return s.app.appCodec
}
func (s TestSupport) ScopedWasmIBCKeeper() capabilitykeeper.ScopedKeeper {
@ -56,3 +61,11 @@ func (s TestSupport) BankKeeper() bankkeeper.Keeper {
func (s TestSupport) TransferKeeper() ibctransferkeeper.Keeper {
return s.app.transferKeeper
}
func (s TestSupport) GetBaseApp() *baseapp.BaseApp {
return s.app.BaseApp
}
func (s TestSupport) GetTxConfig() client.TxConfig {
return params.MakeEncodingConfig().TxConfig
}

View File

@ -9,8 +9,8 @@ import (
"testing"
"time"
"github.com/CosmWasm/wasmd/x/wasm"
bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/log"
@ -18,6 +18,8 @@ import (
tmtypes "github.com/tendermint/tendermint/types"
dbm "github.com/tendermint/tm-db"
"github.com/CosmWasm/wasmd/x/wasm"
bam "github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
@ -53,7 +55,7 @@ var DefaultConsensusParams = &abci.ConsensusParams{
func setup(withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*WasmApp, GenesisState) {
db := dbm.NewMemDB()
app := NewWasmApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, invCheckPeriod, wasm.EnableAllProposals, EmptyBaseAppOptions{}, opts)
app := NewWasmApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, DefaultNodeHome, invCheckPeriod, MakeEncodingConfig(), wasm.EnableAllProposals, EmptyBaseAppOptions{}, opts)
if withGenesis {
return app, NewDefaultGenesisState()
}
@ -131,6 +133,12 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs
totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt))...)
}
// add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)},
})
// update total supply
bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{})
genesisState[banktypes.ModuleName] = app.appCodec.MustMarshalJSON(bankGenesis)
@ -238,21 +246,11 @@ func createIncrementalAccounts(accNum int) []sdk.AccAddress {
func AddTestAddrsFromPubKeys(app *WasmApp, ctx sdk.Context, pubKeys []cryptotypes.PubKey, accAmt sdk.Int) {
initCoins := sdk.NewCoins(sdk.NewCoin(app.stakingKeeper.BondDenom(ctx), accAmt))
setTotalSupply(app, ctx, accAmt, len(pubKeys))
// fill all the addresses with some coins, set the loose pool tokens simultaneously
for _, pubKey := range pubKeys {
saveAccount(app, ctx, sdk.AccAddress(pubKey.Address()), initCoins)
for _, pk := range pubKeys {
initAccountWithCoins(app, ctx, sdk.AccAddress(pk.Address()), initCoins)
}
}
// setTotalSupply provides the total supply based on accAmt * totalAccounts.
func setTotalSupply(app *WasmApp, ctx sdk.Context, accAmt sdk.Int, totalAccounts int) {
totalSupply := sdk.NewCoins(sdk.NewCoin(app.stakingKeeper.BondDenom(ctx), accAmt.MulRaw(int64(totalAccounts))))
prevSupply := app.bankKeeper.GetSupply(ctx)
app.bankKeeper.SetSupply(ctx, banktypes.NewSupply(prevSupply.GetTotal().Add(totalSupply...)))
}
// AddTestAddrs constructs and returns accNum amount of accounts with an
// initial balance of accAmt in random order
func AddTestAddrs(app *WasmApp, ctx sdk.Context, accNum int, accAmt sdk.Int) []sdk.AccAddress {
@ -269,21 +267,22 @@ func addTestAddrs(app *WasmApp, ctx sdk.Context, accNum int, accAmt sdk.Int, str
testAddrs := strategy(accNum)
initCoins := sdk.NewCoins(sdk.NewCoin(app.stakingKeeper.BondDenom(ctx), accAmt))
setTotalSupply(app, ctx, accAmt, accNum)
// fill all the addresses with some coins, set the loose pool tokens simultaneously
for _, addr := range testAddrs {
saveAccount(app, ctx, addr, initCoins)
initAccountWithCoins(app, ctx, addr, initCoins)
}
return testAddrs
}
// saveAccount saves the provided account into the WasmApp with balance based on initCoins.
func saveAccount(app *WasmApp, ctx sdk.Context, addr sdk.AccAddress, initCoins sdk.Coins) {
acc := app.accountKeeper.NewAccountWithAddress(ctx, addr)
app.accountKeeper.SetAccount(ctx, acc)
err := app.bankKeeper.AddCoins(ctx, addr, initCoins)
func initAccountWithCoins(app *WasmApp, ctx sdk.Context, addr sdk.AccAddress, coins sdk.Coins) {
err := app.bankKeeper.MintCoins(ctx, minttypes.ModuleName, coins)
if err != nil {
panic(err)
}
err = app.bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, coins)
if err != nil {
panic(err)
}
@ -381,6 +380,43 @@ func SignCheckDeliver(
return gInfo, res, err
}
// SignAndDeliver signs and delivers a transaction. No simulation occurs as the
// ibc testing package causes checkState and deliverState to diverge in block time.
func SignAndDeliver(
t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg,
chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey,
) (sdk.GasInfo, *sdk.Result, error) {
tx, err := helpers.GenTx(
txCfg,
msgs,
sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)},
2*DefaultGas,
chainID,
accNums,
accSeqs,
priv...,
)
require.NoError(t, err)
// Simulate a sending a transaction and committing a block
app.BeginBlock(abci.RequestBeginBlock{Header: header})
gInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx)
if expPass {
require.NoError(t, err)
require.NotNil(t, res)
} else {
require.Error(t, err)
require.Nil(t, res)
}
app.EndBlock(abci.RequestEndBlock{})
app.Commit()
return gInfo, res, err
}
// GenSequenceOfTxs generates a set of signed transactions of messages, such
// that they differ only by having the sequence numbers incremented between
// every transaction.
@ -449,3 +485,31 @@ type EmptyBaseAppOptions struct{}
func (ao EmptyBaseAppOptions) Get(o string) interface{} {
return nil
}
// FundAccount is a utility function that funds an account by minting and
// sending the coins to the address. This should be used for testing purposes
// only!
//
// Instead of using the mint module account, which has the
// permission of minting, create a "faucet" account. (@fdymylja)
func FundAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, addr sdk.AccAddress, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil {
return err
}
return bankKeeper.SendCoinsFromModuleToAccount(ctx, minttypes.ModuleName, addr, amounts)
}
// FundModuleAccount is a utility function that funds a module account by
// minting and sending the coins to the address. This should be used for testing
// purposes only!
//
// Instead of using the mint module account, which has the
// permission of minting, create a "faucet" account. (@fdymylja)
func FundModuleAccount(bankKeeper bankkeeper.Keeper, ctx sdk.Context, recipientMod string, amounts sdk.Coins) error {
if err := bankKeeper.MintCoins(ctx, minttypes.ModuleName, amounts); err != nil {
return err
}
return bankKeeper.SendCoinsFromModuleToModule(ctx, minttypes.ModuleName, recipientMod, amounts)
}

View File

@ -27,7 +27,8 @@ import (
)
func setup(db dbm.DB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option) (*app.WasmApp, app.GenesisState) {
wasmApp := app.NewWasmApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, invCheckPeriod, wasm.EnableAllProposals, app.EmptyBaseAppOptions{}, opts)
encodingConfig := app.MakeEncodingConfig()
wasmApp := app.NewWasmApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, app.DefaultNodeHome, invCheckPeriod, encodingConfig, wasm.EnableAllProposals, app.EmptyBaseAppOptions{}, opts)
if withGenesis {
return wasmApp, app.NewDefaultGenesisState()
}
@ -36,11 +37,10 @@ func setup(db dbm.DB, withGenesis bool, invCheckPeriod uint, opts ...wasm.Option
// SetupWithGenesisAccounts initializes a new WasmApp with the provided genesis
// accounts and possible balances.
func SetupWithGenesisAccounts(db dbm.DB, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *app.WasmApp {
func SetupWithGenesisAccounts(b testing.TB, db dbm.DB, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *app.WasmApp {
wasmApp, genesisState := setup(db, true, 0)
authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs)
encodingConfig := app.MakeEncodingConfig()
appCodec := encodingConfig.Marshaler
appCodec := app.NewTestSupport(b, wasmApp).AppCodec()
genesisState[authtypes.ModuleName] = appCodec.MustMarshalJSON(authGenesis)
@ -111,7 +111,7 @@ func InitializeWasmApp(b testing.TB, db dbm.DB, numAccounts int) AppInfo {
Coins: sdk.NewCoins(sdk.NewInt64Coin(denom, 100000000000)),
}
}
wasmApp := SetupWithGenesisAccounts(db, genAccs, bals...)
wasmApp := SetupWithGenesisAccounts(b, db, genAccs, bals...)
// add wasm contract
height := int64(2)

View File

@ -1,39 +0,0 @@
package main
import (
"context"
"github.com/rs/zerolog"
"github.com/spf13/cobra"
tmcfg "github.com/tendermint/tendermint/config"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
)
// Execute executes the root command of an application. It handles creating a
// server context object with the appropriate server and client objects injected
// into the underlying stdlib Context. It also handles adding core CLI flags,
// specifically the logging flags. It returns an error upon execution failure.
func Execute(rootCmd *cobra.Command, defaultHome string) error {
// NOTE: file copied from cosmos-sdk/server/cmd
// Create and set a client.Context on the command's Context. During the pre-run
// of the root command, a default initialized client.Context is provided to
// seed child command execution with values such as AccountRetriver, Keyring,
// and a Tendermint RPC. This requires the use of a pointer reference when
// getting and setting the client.Context. Ideally, we utilize
// https://github.com/spf13/cobra/pull/1118.
srvCtx := server.NewDefaultContext()
ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{})
ctx = context.WithValue(ctx, server.ServerContextKey, srvCtx)
rootCmd.PersistentFlags().String(flags.FlagLogLevel, zerolog.InfoLevel.String(), "The logging level (trace|debug|info|warn|error|fatal|panic)")
rootCmd.PersistentFlags().String(flags.FlagLogFormat, tmcfg.LogFormatPlain, "The logging format (json|plain)")
executor := tmcli.PrepareBaseCmd(rootCmd, "WM", defaultHome)
return executor.ExecuteContext(ctx)
}

View File

@ -10,7 +10,6 @@ import (
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -40,33 +39,33 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
clientCtx := client.GetClientContextFromCmd(cmd)
depCdc := clientCtx.JSONMarshaler
cdc := depCdc.(codec.Marshaler)
serverCtx := server.GetServerContextFromCmd(cmd)
config := serverCtx.Config
config.SetRoot(clientCtx.HomeDir)
var kr keyring.Keyring
addr, err := sdk.AccAddressFromBech32(args[0])
if err != nil {
inBuf := bufio.NewReader(cmd.InOrStdin())
keyringBackend, err := cmd.Flags().GetString(flags.FlagKeyringBackend)
if err != nil {
return err
return fmt.Errorf("failed to parse keyring backend: %w", err)
}
if keyringBackend != "" && clientCtx.Keyring == nil {
var err error
kr, err = keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf)
if err != nil {
return err
}
} else {
kr = clientCtx.Keyring
}
// attempt to lookup address from Keybase if no address was provided
kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf)
info, err := kr.Key(args[0])
if err != nil {
return err
return fmt.Errorf("failed to get address from Keyring: %w", err)
}
info, err := kb.Key(args[0])
if err != nil {
return fmt.Errorf("failed to get address from Keybase: %w", err)
}
addr = info.GetAddress()
}
@ -77,15 +76,15 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
vestingStart, err := cmd.Flags().GetInt64(flagVestingStart)
if err != nil {
return err
return fmt.Errorf("failed to parse vesting start: %w", err)
}
vestingEnd, err := cmd.Flags().GetInt64(flagVestingEnd)
if err != nil {
return err
return fmt.Errorf("failed to parse vesting end: %w", err)
}
vestingAmtStr, err := cmd.Flags().GetString(flagVestingAmt)
if err != nil {
return err
return fmt.Errorf("failed to parse vesting amount: %w", err)
}
vestingAmt, err := sdk.ParseCoinsNormalized(vestingAmtStr)
@ -131,7 +130,7 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
return fmt.Errorf("failed to unmarshal genesis state: %w", err)
}
authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState)
authGenState := authtypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)
accs, err := authtypes.UnpackAccounts(authGenState.Accounts)
if err != nil {
@ -153,18 +152,19 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa
}
authGenState.Accounts = genAccs
authGenStateBz, err := cdc.MarshalJSON(&authGenState)
authGenStateBz, err := clientCtx.Codec.MarshalJSON(&authGenState)
if err != nil {
return fmt.Errorf("failed to marshal auth genesis state: %w", err)
}
appState[authtypes.ModuleName] = authGenStateBz
bankGenState := banktypes.GetGenesisStateFromAppState(depCdc, appState)
bankGenState := banktypes.GetGenesisStateFromAppState(clientCtx.Codec, appState)
bankGenState.Balances = append(bankGenState.Balances, balances)
bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances)
bankGenState.Supply = bankGenState.Supply.Add(balances.Coins...)
bankGenStateBz, err := cdc.MarshalJSON(bankGenState)
bankGenStateBz, err := clientCtx.Codec.MarshalJSON(bankGenState)
if err != nil {
return fmt.Errorf("failed to marshal bank genesis state: %w", err)
}

View File

@ -4,6 +4,7 @@ import (
"os"
"github.com/cosmos/cosmos-sdk/server"
svrcmd "github.com/cosmos/cosmos-sdk/server/cmd"
"github.com/CosmWasm/wasmd/app"
)
@ -11,7 +12,7 @@ import (
func main() {
rootCmd, _ := NewRootCmd()
if err := Execute(rootCmd, app.DefaultNodeHome); err != nil {
if err := svrcmd.Execute(rootCmd, app.DefaultNodeHome); err != nil {
switch e := err.(type) {
case server.ErrorCode:
os.Exit(e.Code)

View File

@ -6,21 +6,9 @@ import (
"os"
"path/filepath"
"github.com/prometheus/client_golang/prometheus"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli"
bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli"
"github.com/spf13/cast"
"github.com/spf13/cobra"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/config"
"github.com/cosmos/cosmos-sdk/client/debug"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/keys"
@ -31,47 +19,72 @@ import (
"github.com/cosmos/cosmos-sdk/store"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
authclient "github.com/cosmos/cosmos-sdk/x/auth/client"
authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/crisis"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/cast"
"github.com/spf13/cobra"
tmcli "github.com/tendermint/tendermint/libs/cli"
"github.com/tendermint/tendermint/libs/log"
dbm "github.com/tendermint/tm-db"
"github.com/CosmWasm/wasmd/app"
"github.com/CosmWasm/wasmd/app/params"
"github.com/CosmWasm/wasmd/x/wasm"
clientcodec "github.com/CosmWasm/wasmd/x/wasm/client/codec"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
wasmtypes "github.com/CosmWasm/wasmd/x/wasm/types"
)
// NewRootCmd creates a new root command for wasmd. It is called once in the
// main function.
func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
func NewRootCmd() (*cobra.Command, params.EncodingConfig) {
encodingConfig := app.MakeEncodingConfig()
config := sdk.GetConfig()
config.SetBech32PrefixForAccount(app.Bech32PrefixAccAddr, app.Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(app.Bech32PrefixValAddr, app.Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(app.Bech32PrefixConsAddr, app.Bech32PrefixConsPub)
config.Seal()
cfg := sdk.GetConfig()
cfg.SetBech32PrefixForAccount(app.Bech32PrefixAccAddr, app.Bech32PrefixAccPub)
cfg.SetBech32PrefixForValidator(app.Bech32PrefixValAddr, app.Bech32PrefixValPub)
cfg.SetBech32PrefixForConsensusNode(app.Bech32PrefixConsAddr, app.Bech32PrefixConsPub)
cfg.SetAddressVerifier(wasmtypes.VerifyAddressLen())
cfg.Seal()
initClientCtx := client.Context{}.
WithJSONMarshaler(clientcodec.NewProtoCodec(encodingConfig.Marshaler, encodingConfig.InterfaceRegistry)).
WithCodec(clientcodec.NewProtoCodec(encodingConfig.Marshaler, encodingConfig.InterfaceRegistry)).
WithInterfaceRegistry(encodingConfig.InterfaceRegistry).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
WithAccountRetriever(authtypes.AccountRetriever{}).
WithBroadcastMode(flags.BroadcastBlock).
WithHomeDir(app.DefaultNodeHome)
WithHomeDir(app.DefaultNodeHome).
WithViper("")
rootCmd := &cobra.Command{
Use: version.AppName,
Short: "Wasm Daemon (server)",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// set the default command outputs
cmd.SetOut(cmd.OutOrStdout())
cmd.SetErr(cmd.ErrOrStderr())
initClientCtx, err := client.ReadPersistentCommandFlags(initClientCtx, cmd.Flags())
if err != nil {
return err
}
initClientCtx, err = config.ReadFromClientConfig(initClientCtx)
if err != nil {
return err
}
if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
return err
}
return server.InterceptConfigsPreRunHandler(cmd)
return server.InterceptConfigsPreRunHandler(cmd, "", nil)
},
}
@ -80,13 +93,10 @@ func NewRootCmd() (*cobra.Command, app.EncodingConfig) {
return rootCmd, encodingConfig
}
func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {
authclient.Codec = encodingConfig.Marshaler
func initRootCmd(rootCmd *cobra.Command, encodingConfig params.EncodingConfig) {
rootCmd.AddCommand(
genutilcli.InitCmd(app.ModuleBasics, app.DefaultNodeHome),
genutilcli.CollectGenTxsCmd(banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.MigrateGenesisCmd(),
genutilcli.GenTxCmd(app.ModuleBasics, encodingConfig.TxConfig, banktypes.GenesisBalancesIterator{}, app.DefaultNodeHome),
genutilcli.ValidateGenesisCmd(app.ModuleBasics),
AddGenesisAccountCmd(app.DefaultNodeHome),
@ -94,9 +104,13 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) {
tmcli.NewCompletionCmd(rootCmd, true),
// testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}),
debug.Cmd(),
config.Cmd(),
)
server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, createWasmAppAndExport, addModuleInitFlags)
ac := appCreator{
encCfg: encodingConfig,
}
server.AddCommands(rootCmd, app.DefaultNodeHome, ac.newApp, ac.appExport, addModuleInitFlags)
// add keybase, auxiliary RPC, query, and tx child commands
rootCmd.AddCommand(
@ -121,9 +135,9 @@ func queryCommand() *cobra.Command {
SuggestionsMinimumDistance: 2,
RunE: client.ValidateCmd,
}
cmd.AddCommand(
authcmd.GetAccountCmd(),
flags.LineBreak,
rpc.ValidatorCommand(),
rpc.BlockCommand(),
authcmd.QueryTxsByEventsCmd(),
@ -146,39 +160,34 @@ func txCommand() *cobra.Command {
}
cmd.AddCommand(
bankcmd.NewSendTxCmd(),
flags.LineBreak,
authcmd.GetSignCommand(),
authcmd.GetSignBatchCommand(),
authcmd.GetMultiSignCommand(),
authcmd.GetMultiSignBatchCmd(),
authcmd.GetValidateSignaturesCommand(),
flags.LineBreak,
authcmd.GetBroadcastCommand(),
authcmd.GetEncodeCommand(),
authcmd.GetDecodeCommand(),
flags.LineBreak,
vestingcli.GetTxCmd(),
)
// add modules' tx commands
app.ModuleBasics.AddTxCommands(cmd)
// remove auth and bank commands as they're mounted under the root tx command
var cmdsToRemove []*cobra.Command
for _, cmd := range cmd.Commands() {
if cmd.Use == authtypes.ModuleName || cmd.Use == banktypes.ModuleName {
cmdsToRemove = append(cmdsToRemove, cmd)
}
}
cmd.RemoveCommand(cmdsToRemove...)
cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID")
return cmd
}
func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
type appCreator struct {
encCfg params.EncodingConfig
}
func (ac appCreator) newApp(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
appOpts servertypes.AppOptions,
) servertypes.Application {
var cache sdk.MultiStorePersistentCache
if cast.ToBool(appOpts.Get(server.FlagInterBlockCache)) {
@ -212,6 +221,7 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty
return app.NewWasmApp(logger, db, traceStore, true, skipUpgradeHeights,
cast.ToString(appOpts.Get(flags.FlagHome)),
cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
ac.encCfg,
app.GetEnabledProposals(),
appOpts,
wasmOpts,
@ -229,24 +239,42 @@ func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts serverty
)
}
func createWasmAppAndExport(
logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailAllowedAddrs []string,
appOpts servertypes.AppOptions) (servertypes.ExportedApp, error) {
func (ac appCreator) appExport(
logger log.Logger,
db dbm.DB,
traceStore io.Writer,
height int64,
forZeroHeight bool,
jailAllowedAddrs []string,
appOpts servertypes.AppOptions,
) (servertypes.ExportedApp, error) {
var wasmApp *app.WasmApp
homePath, ok := appOpts.Get(flags.FlagHome).(string)
if !ok || homePath == "" {
return servertypes.ExportedApp{}, errors.New("application home not set")
return servertypes.ExportedApp{}, errors.New("application home is not set")
}
var emptyWasmOpts []wasm.Option
if height != -1 {
wasmApp = app.NewWasmApp(logger, db, traceStore, false, map[int64]bool{}, homePath, uint(1), app.GetEnabledProposals(), appOpts, emptyWasmOpts)
loadLatest := height == -1
var emptyWasmOpts []wasm.Option
wasmApp = app.NewWasmApp(
logger,
db,
traceStore,
loadLatest,
map[int64]bool{},
homePath,
cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)),
ac.encCfg,
app.GetEnabledProposals(),
appOpts,
emptyWasmOpts,
)
if height != -1 {
if err := wasmApp.LoadHeight(height); err != nil {
return servertypes.ExportedApp{}, err
}
} else {
wasmApp = app.NewWasmApp(logger, db, traceStore, true, map[int64]bool{}, homePath, uint(1), app.GetEnabledProposals(), appOpts, emptyWasmOpts)
}
return wasmApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs)

View File

@ -12,7 +12,7 @@ NEW_ACCOUNT=$(wasmd keys show fred -a)
wasmd q bank balances "$NEW_ACCOUNT" -o json || true
echo "## Transfer tokens"
wasmd tx send validator "$NEW_ACCOUNT" 1ustake --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block | jq
wasmd tx bank send validator "$NEW_ACCOUNT" 1ustake --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block -o json | jq
echo "## Check balance again"
wasmd q bank balances "$NEW_ACCOUNT" -o json | jq

View File

@ -6,7 +6,7 @@ DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
echo "-----------------------"
echo "## Add new CosmWasm contract"
RESP=$(wasmd tx wasm store "$DIR/../../x/wasm/keeper/testdata/hackatom.wasm" \
--from validator --gas 1500000 -y --chain-id=testing --node=http://localhost:26657 -b block)
--from validator --gas 1500000 -y --chain-id=testing --node=http://localhost:26657 -b block -o json)
CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[1].attributes[-1].value')
echo "* Code id: $CODE_ID"
@ -23,7 +23,7 @@ echo "## Create new contract instance"
INIT="{\"verifier\":\"$(wasmd keys show validator -a)\", \"beneficiary\":\"$(wasmd keys show fred -a)\"}"
wasmd tx wasm instantiate "$CODE_ID" "$INIT" --admin="$(wasmd keys show validator -a)" \
--from validator --amount="100ustake" --label "local0.1.0" \
--gas 1000000 -y --chain-id=testing -b block | jq
--gas 1000000 -y --chain-id=testing -b block -o json | jq
CONTRACT=$(wasmd query wasm list-contract-by-code "$CODE_ID" -o json | jq -r '.contracts[-1]')
echo "* Contract address: $CONTRACT"
@ -41,28 +41,28 @@ echo "## Execute contract $CONTRACT"
MSG='{"release":{}}'
wasmd tx wasm execute "$CONTRACT" "$MSG" \
--from validator \
--gas 1000000 -y --chain-id=testing -b block | jq
--gas 1000000 -y --chain-id=testing -b block -o json | jq
echo "-----------------------"
echo "## Set new admin"
echo "### Query old admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')"
echo "### Update contract"
wasmd tx wasm set-contract-admin "$CONTRACT" "$(wasmd keys show fred -a)" \
--from validator -y --chain-id=testing -b block | jq
echo "### Query new admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.admin')"
--from validator -y --chain-id=testing -b block -o json | jq
echo "### Query new admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')"
echo "-----------------------"
echo "## Migrate contract"
echo "### Upload new code"
RESP=$(wasmd tx wasm store "$DIR/../../x/wasm/keeper/testdata/burner.wasm" \
--from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block)
--from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block -o json)
BURNER_CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[1].attributes[-1].value')
echo "### Migrate to code id: $BURNER_CODE_ID"
DEST_ACCOUNT=$(wasmd keys show fred -a)
wasmd tx wasm migrate "$CONTRACT" "$BURNER_CODE_ID" "{\"payout\": \"$DEST_ACCOUNT\"}" --from fred \
--chain-id=testing -b block -y | jq
--chain-id=testing -b block -y -o json | jq
echo "### Query destination account: $BURNER_CODE_ID"
wasmd q bank balances "$DEST_ACCOUNT" -o json | jq
@ -74,8 +74,8 @@ wasmd q wasm contract-history "$CONTRACT" -o json | jq
echo "-----------------------"
echo "## Clear contract admin"
echo "### Query old admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.admin')"
echo "### Query old admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')"
echo "### Update contract"
wasmd tx wasm clear-contract-admin "$CONTRACT" \
--from fred -y --chain-id=testing -b block | jq
echo "### Query new admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.admin')"
--from fred -y --chain-id=testing -b block -o json | jq
echo "### Query new admin: $(wasmd q wasm contract "$CONTRACT" -o json | jq -r '.contract_info.admin')"

75
go.mod
View File

@ -4,8 +4,9 @@ go 1.17
require (
github.com/CosmWasm/wasmvm v1.0.0-beta5
github.com/cosmos/cosmos-sdk v0.42.11
github.com/cosmos/cosmos-sdk v0.45.0
github.com/cosmos/iavl v0.17.3
github.com/cosmos/ibc-go/v2 v2.0.2
github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b
github.com/gogo/protobuf v1.3.3
github.com/golang/protobuf v1.5.2
@ -16,32 +17,33 @@ require (
github.com/prometheus/client_golang v1.11.0
github.com/rakyll/statik v0.1.7
github.com/regen-network/cosmos-proto v0.3.1
github.com/rs/zerolog v1.26.0
github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa
github.com/spf13/cast v1.4.1
github.com/spf13/cobra v1.1.3
github.com/spf13/cobra v1.2.1
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.9.0
github.com/spf13/viper v1.10.1
github.com/stretchr/testify v1.7.0
github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca
github.com/tendermint/tendermint v0.34.14
github.com/tendermint/tm-db v0.6.4
google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71
google.golang.org/grpc v1.42.0
github.com/tendermint/tendermint v0.34.15
github.com/tendermint/tm-db v0.6.6
google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa
google.golang.org/grpc v1.43.0
gopkg.in/yaml.v2 v2.4.0
)
require (
filippo.io/edwards25519 v1.0.0-beta.2 // indirect
github.com/99designs/keyring v1.1.6 // indirect
github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d // indirect
github.com/DataDog/zstd v1.4.5 // indirect
github.com/Workiva/go-datastructures v1.0.52 // indirect
github.com/armon/go-metrics v0.3.8 // indirect
github.com/Workiva/go-datastructures v1.0.53 // indirect
github.com/armon/go-metrics v0.3.10 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/speakeasy v0.1.0 // indirect
github.com/btcsuite/btcd v0.22.0-beta // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/coinbase/rosetta-sdk-go v0.7.0 // indirect
github.com/confio/ics23/go v0.6.6 // indirect
github.com/cosmos/btcutil v1.0.4 // indirect
github.com/cosmos/go-bip39 v1.0.0 // indirect
@ -49,14 +51,16 @@ require (
github.com/cosmos/ledger-go v0.9.2 // indirect
github.com/danieljoos/wincred v1.0.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/desertbit/timer v0.0.0-20180107155436-c41aec40b27f // indirect
github.com/dgraph-io/badger/v2 v2.2007.2 // indirect
github.com/dgraph-io/ristretto v0.0.3 // indirect
github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect
github.com/dustin/go-humanize v1.0.0 // indirect
github.com/felixge/httpsnoop v1.0.1 // indirect
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/go-kit/kit v0.10.0 // indirect
github.com/go-logfmt/logfmt v0.5.0 // indirect
github.com/go-kit/kit v0.12.0 // indirect
github.com/go-kit/log v0.2.0 // indirect
github.com/go-logfmt/logfmt v0.5.1 // indirect
github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 // indirect
github.com/gogo/gateway v1.1.0 // indirect
github.com/golang/snappy v0.0.3 // indirect
@ -68,30 +72,33 @@ require (
github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c // indirect
github.com/gtank/merlin v0.1.1 // indirect
github.com/gtank/ristretto255 v0.1.2 // indirect
github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/hdevalence/ed25519consensus v0.0.0-20210204194344-59a8610d2b87 // indirect
github.com/improbable-eng/grpc-web v0.14.1 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jmhodges/levigo v1.0.0 // indirect
github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d // indirect
github.com/lib/pq v1.2.0 // indirect
github.com/klauspost/compress v1.13.6 // indirect
github.com/lib/pq v1.10.4 // indirect
github.com/libp2p/go-buffer-pool v0.0.2 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 // indirect
github.com/minio/highwayhash v1.0.1 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.4.2 // indirect
github.com/minio/highwayhash v1.0.2 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/mtibben/percent v0.2.1 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.26.0 // indirect
github.com/prometheus/procfs v0.6.0 // indirect
github.com/prometheus/common v0.30.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 // indirect
github.com/rs/cors v1.7.0 // indirect
github.com/rs/cors v1.8.0 // indirect
github.com/rs/zerolog v1.26.0 // indirect
github.com/sasha-s/go-deadlock v0.2.1-0.20190427202633-1595213edefa // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
@ -101,24 +108,30 @@ require (
github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 // indirect
github.com/tendermint/go-amino v0.16.0 // indirect
github.com/zondax/hid v0.9.0 // indirect
go.etcd.io/bbolt v1.3.5 // indirect
golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect
golang.org/x/net v0.0.0-20210903162142-ad29c8ab022f // indirect
golang.org/x/sys v0.0.0-20210903071746-97244b99971b // indirect
go.etcd.io/bbolt v1.3.6 // indirect
golang.org/x/crypto v0.0.0-20210915214749-c084706c2272 // indirect
golang.org/x/net v0.0.0-20211005001312-d4b1ae081e3b // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 // indirect
golang.org/x/text v0.3.6 // indirect
golang.org/x/text v0.3.7 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/ini.v1 v1.63.2 // indirect
gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
nhooyr.io/websocket v1.8.6 // indirect
)
replace (
github.com/99designs/keyring => github.com/cosmos/keyring v1.1.7-0.20210622111912-ef00f8ac3d76
github.com/confio/ics23/go => github.com/confio/ics23/go v0.6.6
github.com/cosmos/cosmos-sdk => github.com/cosmos/cosmos-sdk v0.42.11
github.com/cosmos/cosmos-sdk => github.com/cosmos/cosmos-sdk v0.45.0
github.com/cosmos/go-bip39 => github.com/cosmos/go-bip39 v1.0.0
github.com/cosmos/iavl => github.com/cosmos/iavl v0.17.3
// Fix upstream GHSA-h395-qcrw-5vmq vulnerability.
// TODO Remove it: https://github.com/cosmos/cosmos-sdk/issues/10409
github.com/gin-gonic/gin => github.com/gin-gonic/gin v1.7.0
// latest grpc doesn't work with with our modified proto compiler, so we need to enforce
// the following version across all dependencies.
github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.3-alpha.regen.1
github.com/tendermint/tendermint => github.com/tendermint/tendermint v0.34.14
github.com/urfave/cli => github.com/urfave/cli v1.22.1
github.com/tendermint/tendermint => github.com/tendermint/tendermint v0.34.15
google.golang.org/grpc => google.golang.org/grpc v1.33.2
)

454
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
# Third party
Contain the protobuf dependencies
## Cosmos-SDK
* [/proto dir](https://github.com/cosmos/cosmos-sdk/tree/master/proto)
* [/third_party dir](https://github.com/cosmos/cosmos-sdk/tree/master/third_party/proto)
Credits and :bouquet: to the original authors

View File

@ -1,6 +1,7 @@
syntax = "proto3";
package cosmos.auth.v1beta1;
import "cosmos/base/query/v1beta1/pagination.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "google/api/annotations.proto";
@ -11,6 +12,13 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/auth/types";
// Query defines the gRPC querier service.
service Query {
// Accounts returns all the existing accounts
//
// Since: cosmos-sdk 0.43
rpc Accounts(QueryAccountsRequest) returns (QueryAccountsResponse) {
option (google.api.http).get = "/cosmos/auth/v1beta1/accounts";
}
// Account returns account details based on address.
rpc Account(QueryAccountRequest) returns (QueryAccountResponse) {
option (google.api.http).get = "/cosmos/auth/v1beta1/accounts/{address}";
@ -22,6 +30,25 @@ service Query {
}
}
// QueryAccountsRequest is the request type for the Query/Accounts RPC method.
//
// Since: cosmos-sdk 0.43
message QueryAccountsRequest {
// pagination defines an optional pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryAccountsResponse is the response type for the Query/Accounts RPC method.
//
// Since: cosmos-sdk 0.43
message QueryAccountsResponse {
// accounts are the existing accounts
repeated google.protobuf.Any accounts = 1 [(cosmos_proto.accepts_interface) = "AccountI"];
// pagination defines the pagination in the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
// QueryAccountRequest is the request type for the Query/Account RPC method.
message QueryAccountRequest {
option (gogoproto.equal) = false;

View File

@ -0,0 +1,27 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.authz.v1beta1;
import "cosmos_proto/cosmos.proto";
import "google/protobuf/timestamp.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
option (gogoproto.goproto_getters_all) = false;
// GenericAuthorization gives the grantee unrestricted permissions to execute
// the provided method on behalf of the granter's account.
message GenericAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
// Msg, identified by it's type URL, to grant unrestricted permissions to execute
string msg = 1;
}
// Grant gives permissions to execute
// the provide method with expiration time.
message Grant {
google.protobuf.Any authorization = 1 [(cosmos_proto.accepts_interface) = "Authorization"];
google.protobuf.Timestamp expiration = 2 [(gogoproto.stdtime) = true, (gogoproto.nullable) = false];
}

View File

@ -0,0 +1,25 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.authz.v1beta1;
option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
// EventGrant is emitted on Msg/Grant
message EventGrant {
// Msg type URL for which an autorization is granted
string msg_type_url = 2;
// Granter account address
string granter = 3;
// Grantee account address
string grantee = 4;
}
// EventRevoke is emitted on Msg/Revoke
message EventRevoke {
// Msg type URL for which an autorization is revoked
string msg_type_url = 2;
// Granter account address
string granter = 3;
// Grantee account address
string grantee = 4;
}

View File

@ -0,0 +1,24 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.authz.v1beta1;
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
// GenesisState defines the authz module's genesis state.
message GenesisState {
repeated GrantAuthorization authorization = 1 [(gogoproto.nullable) = false];
}
// GrantAuthorization defines the GenesisState/GrantAuthorization type.
message GrantAuthorization {
string granter = 1;
string grantee = 2;
google.protobuf.Any authorization = 3 [(cosmos_proto.accepts_interface) = "Authorization"];
google.protobuf.Timestamp expiration = 4 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
}

View File

@ -0,0 +1,35 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.authz.v1beta1;
import "google/api/annotations.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "cosmos/authz/v1beta1/authz.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
// Query defines the gRPC querier service.
service Query {
// Returns list of `Authorization`, granted to the grantee by the granter.
rpc Grants(QueryGrantsRequest) returns (QueryGrantsResponse) {
option (google.api.http).get = "/cosmos/authz/v1beta1/grants";
}
}
// QueryGrantsRequest is the request type for the Query/Grants RPC method.
message QueryGrantsRequest {
string granter = 1;
string grantee = 2;
// Optional, msg_type_url, when set, will query only grants matching given msg type.
string msg_type_url = 3;
// pagination defines an pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 4;
}
// QueryGrantsResponse is the response type for the Query/Authorizations RPC method.
message QueryGrantsResponse {
// authorizations is a list of grants granted for grantee by granter.
repeated cosmos.authz.v1beta1.Grant grants = 1;
// pagination defines an pagination for the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}

View File

@ -0,0 +1,70 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.authz.v1beta1;
import "cosmos_proto/cosmos.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/any.proto";
import "cosmos/base/abci/v1beta1/abci.proto";
import "cosmos/authz/v1beta1/authz.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/authz";
option (gogoproto.goproto_getters_all) = false;
// Msg defines the authz Msg service.
service Msg {
// Grant grants the provided authorization to the grantee on the granter's
// account with the provided expiration time. If there is already a grant
// for the given (granter, grantee, Authorization) triple, then the grant
// will be overwritten.
rpc Grant(MsgGrant) returns (MsgGrantResponse);
// Exec attempts to execute the provided messages using
// authorizations granted to the grantee. Each message should have only
// one signer corresponding to the granter of the authorization.
rpc Exec(MsgExec) returns (MsgExecResponse);
// Revoke revokes any authorization corresponding to the provided method name on the
// granter's account that has been granted to the grantee.
rpc Revoke(MsgRevoke) returns (MsgRevokeResponse);
}
// MsgGrant is a request type for Grant method. It declares authorization to the grantee
// on behalf of the granter with the provided expiration time.
message MsgGrant {
string granter = 1;
string grantee = 2;
cosmos.authz.v1beta1.Grant grant = 3 [(gogoproto.nullable) = false];
}
// MsgExecResponse defines the Msg/MsgExecResponse response type.
message MsgExecResponse {
repeated bytes results = 1;
}
// MsgExec attempts to execute the provided messages using
// authorizations granted to the grantee. Each message should have only
// one signer corresponding to the granter of the authorization.
message MsgExec {
string grantee = 1;
// Authorization Msg requests to execute. Each msg must implement Authorization interface
// The x/authz will try to find a grant matching (msg.signers[0], grantee, MsgTypeURL(msg))
// triple and validate it.
repeated google.protobuf.Any msgs = 2 [(cosmos_proto.accepts_interface) = "sdk.Msg, authz.Authorization"];
}
// MsgGrantResponse defines the Msg/MsgGrant response type.
message MsgGrantResponse {}
// MsgRevoke revokes any authorization with the provided sdk.Msg type on the
// granter's account with that has been granted to the grantee.
message MsgRevoke {
string granter = 1;
string grantee = 2;
string msg_type_url = 3;
}
// MsgRevokeResponse defines the Msg/MsgRevokeResponse response type.
message MsgRevokeResponse {}

View File

@ -0,0 +1,19 @@
syntax = "proto3";
package cosmos.bank.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/bank/types";
// SendAuthorization allows the grantee to spend up to spend_limit coins from
// the granter's account.
//
// Since: cosmos-sdk 0.43
message SendAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
repeated cosmos.base.v1beta1.Coin spend_limit = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
}

View File

@ -45,12 +45,14 @@ message Output {
// Supply represents a struct that passively keeps track of the total supply
// amounts in the network.
// This message is deprecated now that supply is indexed by denom.
message Supply {
option (gogoproto.equal) = true;
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
option deprecated = true;
option (cosmos_proto.implements_interface) = "*github.com/cosmos/cosmos-sdk/x/bank/exported.SupplyI";
option (gogoproto.equal) = true;
option (gogoproto.goproto_getters) = false;
option (cosmos_proto.implements_interface) = "*github.com/cosmos/cosmos-sdk/x/bank/legacy/v040.SupplyI";
repeated cosmos.base.v1beta1.Coin total = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
@ -82,4 +84,13 @@ message Metadata {
// display indicates the suggested denom that should be
// displayed in clients.
string display = 4;
// name defines the name of the token (eg: Cosmos Atom)
//
// Since: cosmos-sdk 0.43
string name = 5;
// symbol is the token symbol usually shown on exchanges (eg: ATOM). This can
// be the same as the display.
//
// Since: cosmos-sdk 0.43
string symbol = 6;
}

View File

@ -15,7 +15,8 @@ message GenesisState {
// balances is an array containing the balances of all the accounts.
repeated Balance balances = 2 [(gogoproto.nullable) = false];
// supply represents the total supply.
// supply represents the total supply. If it is left empty, then supply will be calculated based on the provided
// balances. Otherwise, it will be used to validate that the sum of the balances equals this amount.
repeated cosmos.base.v1beta1.Coin supply = 3
[(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins", (gogoproto.nullable) = false];

View File

@ -13,7 +13,7 @@ option go_package = "github.com/cosmos/cosmos-sdk/x/bank/types";
service Query {
// Balance queries the balance of a single coin for a single account.
rpc Balance(QueryBalanceRequest) returns (QueryBalanceResponse) {
option (google.api.http).get = "/cosmos/bank/v1beta1/balances/{address}/{denom}";
option (google.api.http).get = "/cosmos/bank/v1beta1/balances/{address}/by_denom";
}
// AllBalances queries the balance of all coins for a single account.
@ -49,7 +49,7 @@ service Query {
// QueryBalanceRequest is the request type for the Query/Balance RPC method.
message QueryBalanceRequest {
option (gogoproto.equal) = false;
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// address is the address to query balances for.
@ -67,7 +67,7 @@ message QueryBalanceResponse {
// QueryBalanceRequest is the request type for the Query/AllBalances RPC method.
message QueryAllBalancesRequest {
option (gogoproto.equal) = false;
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// address is the address to query balances for.
@ -82,7 +82,7 @@ message QueryAllBalancesRequest {
message QueryAllBalancesResponse {
// balances is the balances of all the coins.
repeated cosmos.base.v1beta1.Coin balances = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
// pagination defines the pagination in the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
@ -90,14 +90,27 @@ message QueryAllBalancesResponse {
// QueryTotalSupplyRequest is the request type for the Query/TotalSupply RPC
// method.
message QueryTotalSupplyRequest {}
message QueryTotalSupplyRequest {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// pagination defines an optional pagination for the request.
//
// Since: cosmos-sdk 0.43
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryTotalSupplyResponse is the response type for the Query/TotalSupply RPC
// method
message QueryTotalSupplyResponse {
// supply is the supply of the coins
repeated cosmos.base.v1beta1.Coin supply = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
// pagination defines the pagination in the response.
//
// Since: cosmos-sdk 0.43
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
// QuerySupplyOfRequest is the request type for the Query/SupplyOf RPC method.

View File

@ -39,6 +39,13 @@ message TxResponse {
// the timestamps of the valid votes in the block.LastCommit. For height == 1,
// it's genesis time.
string timestamp = 12;
// Events defines all the events emitted by processing a transaction. Note,
// these events include those emitted by processing all the messages and those
// emitted from the ante handler. Whereas Logs contains the events, with
// additional metadata, emitted only by processing the messages.
//
// Since: cosmos-sdk 0.42.11, 0.44.5, 0.45
repeated tendermint.abci.Event events = 13 [(gogoproto.nullable) = false];
}
// ABCIMessageLog defines a structure containing an indexed tx ABCI message log.

View File

@ -30,6 +30,11 @@ message PageRequest {
// count_total is only respected when offset is used. It is ignored when key
// is set.
bool count_total = 4;
// reverse is set to true if results are to be returned in the descending order.
//
// Since: cosmos-sdk 0.43
bool reverse = 5;
}
// PageResponse is to be embedded in gRPC response messages where the

View File

@ -0,0 +1,218 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.base.reflection.v2alpha1;
import "google/api/annotations.proto";
option go_package = "github.com/cosmos/cosmos-sdk/server/grpc/reflection/v2alpha1";
// AppDescriptor describes a cosmos-sdk based application
message AppDescriptor {
// AuthnDescriptor provides information on how to authenticate transactions on the application
// NOTE: experimental and subject to change in future releases.
AuthnDescriptor authn = 1;
// chain provides the chain descriptor
ChainDescriptor chain = 2;
// codec provides metadata information regarding codec related types
CodecDescriptor codec = 3;
// configuration provides metadata information regarding the sdk.Config type
ConfigurationDescriptor configuration = 4;
// query_services provides metadata information regarding the available queriable endpoints
QueryServicesDescriptor query_services = 5;
// tx provides metadata information regarding how to send transactions to the given application
TxDescriptor tx = 6;
}
// TxDescriptor describes the accepted transaction type
message TxDescriptor {
// fullname is the protobuf fullname of the raw transaction type (for instance the tx.Tx type)
// it is not meant to support polymorphism of transaction types, it is supposed to be used by
// reflection clients to understand if they can handle a specific transaction type in an application.
string fullname = 1;
// msgs lists the accepted application messages (sdk.Msg)
repeated MsgDescriptor msgs = 2;
}
// AuthnDescriptor provides information on how to sign transactions without relying
// on the online RPCs GetTxMetadata and CombineUnsignedTxAndSignatures
message AuthnDescriptor {
// sign_modes defines the supported signature algorithm
repeated SigningModeDescriptor sign_modes = 1;
}
// SigningModeDescriptor provides information on a signing flow of the application
// NOTE(fdymylja): here we could go as far as providing an entire flow on how
// to sign a message given a SigningModeDescriptor, but it's better to think about
// this another time
message SigningModeDescriptor {
// name defines the unique name of the signing mode
string name = 1;
// number is the unique int32 identifier for the sign_mode enum
int32 number = 2;
// authn_info_provider_method_fullname defines the fullname of the method to call to get
// the metadata required to authenticate using the provided sign_modes
string authn_info_provider_method_fullname = 3;
}
// ChainDescriptor describes chain information of the application
message ChainDescriptor {
// id is the chain id
string id = 1;
}
// CodecDescriptor describes the registered interfaces and provides metadata information on the types
message CodecDescriptor {
// interfaces is a list of the registerted interfaces descriptors
repeated InterfaceDescriptor interfaces = 1;
}
// InterfaceDescriptor describes the implementation of an interface
message InterfaceDescriptor {
// fullname is the name of the interface
string fullname = 1;
// interface_accepting_messages contains information regarding the proto messages which contain the interface as
// google.protobuf.Any field
repeated InterfaceAcceptingMessageDescriptor interface_accepting_messages = 2;
// interface_implementers is a list of the descriptors of the interface implementers
repeated InterfaceImplementerDescriptor interface_implementers = 3;
}
// InterfaceImplementerDescriptor describes an interface implementer
message InterfaceImplementerDescriptor {
// fullname is the protobuf queryable name of the interface implementer
string fullname = 1;
// type_url defines the type URL used when marshalling the type as any
// this is required so we can provide type safe google.protobuf.Any marshalling and
// unmarshalling, making sure that we don't accept just 'any' type
// in our interface fields
string type_url = 2;
}
// InterfaceAcceptingMessageDescriptor describes a protobuf message which contains
// an interface represented as a google.protobuf.Any
message InterfaceAcceptingMessageDescriptor {
// fullname is the protobuf fullname of the type containing the interface
string fullname = 1;
// field_descriptor_names is a list of the protobuf name (not fullname) of the field
// which contains the interface as google.protobuf.Any (the interface is the same, but
// it can be in multiple fields of the same proto message)
repeated string field_descriptor_names = 2;
}
// ConfigurationDescriptor contains metadata information on the sdk.Config
message ConfigurationDescriptor {
// bech32_account_address_prefix is the account address prefix
string bech32_account_address_prefix = 1;
}
// MsgDescriptor describes a cosmos-sdk message that can be delivered with a transaction
message MsgDescriptor {
// msg_type_url contains the TypeURL of a sdk.Msg.
string msg_type_url = 1;
}
// ReflectionService defines a service for application reflection.
service ReflectionService {
// GetAuthnDescriptor returns information on how to authenticate transactions in the application
// NOTE: this RPC is still experimental and might be subject to breaking changes or removal in
// future releases of the cosmos-sdk.
rpc GetAuthnDescriptor(GetAuthnDescriptorRequest) returns (GetAuthnDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/authn";
}
// GetChainDescriptor returns the description of the chain
rpc GetChainDescriptor(GetChainDescriptorRequest) returns (GetChainDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/chain";
};
// GetCodecDescriptor returns the descriptor of the codec of the application
rpc GetCodecDescriptor(GetCodecDescriptorRequest) returns (GetCodecDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/codec";
}
// GetConfigurationDescriptor returns the descriptor for the sdk.Config of the application
rpc GetConfigurationDescriptor(GetConfigurationDescriptorRequest) returns (GetConfigurationDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/configuration";
}
// GetQueryServicesDescriptor returns the available gRPC queryable services of the application
rpc GetQueryServicesDescriptor(GetQueryServicesDescriptorRequest) returns (GetQueryServicesDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/query_services";
}
// GetTxDescriptor returns information on the used transaction object and available msgs that can be used
rpc GetTxDescriptor(GetTxDescriptorRequest) returns (GetTxDescriptorResponse) {
option (google.api.http).get = "/cosmos/base/reflection/v1beta1/app_descriptor/tx_descriptor";
}
}
// GetAuthnDescriptorRequest is the request used for the GetAuthnDescriptor RPC
message GetAuthnDescriptorRequest {}
// GetAuthnDescriptorResponse is the response returned by the GetAuthnDescriptor RPC
message GetAuthnDescriptorResponse {
// authn describes how to authenticate to the application when sending transactions
AuthnDescriptor authn = 1;
}
// GetChainDescriptorRequest is the request used for the GetChainDescriptor RPC
message GetChainDescriptorRequest {}
// GetChainDescriptorResponse is the response returned by the GetChainDescriptor RPC
message GetChainDescriptorResponse {
// chain describes application chain information
ChainDescriptor chain = 1;
}
// GetCodecDescriptorRequest is the request used for the GetCodecDescriptor RPC
message GetCodecDescriptorRequest {}
// GetCodecDescriptorResponse is the response returned by the GetCodecDescriptor RPC
message GetCodecDescriptorResponse {
// codec describes the application codec such as registered interfaces and implementations
CodecDescriptor codec = 1;
}
// GetConfigurationDescriptorRequest is the request used for the GetConfigurationDescriptor RPC
message GetConfigurationDescriptorRequest {}
// GetConfigurationDescriptorResponse is the response returned by the GetConfigurationDescriptor RPC
message GetConfigurationDescriptorResponse {
// config describes the application's sdk.Config
ConfigurationDescriptor config = 1;
}
// GetQueryServicesDescriptorRequest is the request used for the GetQueryServicesDescriptor RPC
message GetQueryServicesDescriptorRequest {}
// GetQueryServicesDescriptorResponse is the response returned by the GetQueryServicesDescriptor RPC
message GetQueryServicesDescriptorResponse {
// queries provides information on the available queryable services
QueryServicesDescriptor queries = 1;
}
// GetTxDescriptorRequest is the request used for the GetTxDescriptor RPC
message GetTxDescriptorRequest {}
// GetTxDescriptorResponse is the response returned by the GetTxDescriptor RPC
message GetTxDescriptorResponse {
// tx provides information on msgs that can be forwarded to the application
// alongside the accepted transaction protobuf type
TxDescriptor tx = 1;
}
// QueryServicesDescriptor contains the list of cosmos-sdk queriable services
message QueryServicesDescriptor {
// query_services is a list of cosmos-sdk QueryServiceDescriptor
repeated QueryServiceDescriptor query_services = 1;
}
// QueryServiceDescriptor describes a cosmos-sdk queryable service
message QueryServiceDescriptor {
// fullname is the protobuf fullname of the service descriptor
string fullname = 1;
// is_module describes if this service is actually exposed by an application's module
bool is_module = 2;
// methods provides a list of query service methods
repeated QueryMethodDescriptor methods = 3;
}
// QueryMethodDescriptor describes a queryable method of a query service
// no other info is provided beside method name and tendermint queryable path
// because it would be redundant with the grpc reflection service
message QueryMethodDescriptor {
// name is the protobuf name (not fullname) of the method
string name = 1;
// full_query_path is the path that can be used to query
// this method via tendermint abci.Query
string full_query_path = 2;
}

View File

@ -0,0 +1,16 @@
syntax = "proto3";
package cosmos.base.store.v1beta1;
option go_package = "github.com/cosmos/cosmos-sdk/store/types";
// StoreKVPair is a KVStore KVPair used for listening to state changes (Sets and Deletes)
// It optionally includes the StoreKey for the originating KVStore and a Boolean flag to distinguish between Sets and
// Deletes
//
// Since: cosmos-sdk 0.43
message StoreKVPair {
string store_key = 1; // the store key for the KVStore this pair originates from
bool delete = 2; // true indicates a delete operation, false indicates a set operation
bytes key = 3;
bytes value = 4;
}

View File

@ -116,13 +116,15 @@ message GetNodeInfoResponse {
// VersionInfo is the type for the GetNodeInfoResponse message.
message VersionInfo {
string name = 1;
string app_name = 2;
string version = 3;
string git_commit = 4;
string build_tags = 5;
string go_version = 6;
repeated Module build_deps = 7;
string name = 1;
string app_name = 2;
string version = 3;
string git_commit = 4;
string build_tags = 5;
string go_version = 6;
repeated Module build_deps = 7;
// Since: cosmos-sdk 0.43
string cosmos_sdk_version = 8;
}
// Module is the type for VersionInfo

View File

@ -5,18 +5,19 @@ import "gogoproto/gogo.proto";
option go_package = "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519";
// PubKey defines a ed25519 public key
// Key is the compressed form of the pubkey. The first byte depends is a 0x02 byte
// if the y-coordinate is the lexicographically largest of the two associated with
// the x-coordinate. Otherwise the first byte is a 0x03.
// This prefix is followed with the x-coordinate.
// PubKey is an ed25519 public key for handling Tendermint keys in SDK.
// It's needed for Any serialization and SDK compatibility.
// It must not be used in a non Tendermint key context because it doesn't implement
// ADR-28. Nevertheless, you will like to use ed25519 in app user level
// then you must create a new proto message and follow ADR-28 for Address construction.
message PubKey {
option (gogoproto.goproto_stringer) = false;
bytes key = 1 [(gogoproto.casttype) = "crypto/ed25519.PublicKey"];
}
// PrivKey defines a ed25519 private key.
// Deprecated: PrivKey defines a ed25519 private key.
// NOTE: ed25519 keys must not be used in SDK apps except in a tendermint validator context.
message PrivKey {
bytes key = 1 [(gogoproto.casttype) = "crypto/ed25519.PrivateKey"];
}

View File

@ -0,0 +1,23 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.crypto.secp256r1;
import "gogoproto/gogo.proto";
option go_package = "github.com/cosmos/cosmos-sdk/crypto/keys/secp256r1";
option (gogoproto.messagename_all) = true;
option (gogoproto.goproto_stringer_all) = false;
option (gogoproto.goproto_getters_all) = false;
// PubKey defines a secp256r1 ECDSA public key.
message PubKey {
// Point on secp256r1 curve in a compressed representation as specified in section
// 4.3.6 of ANSI X9.62: https://webstore.ansi.org/standards/ascx9/ansix9621998
bytes key = 1 [(gogoproto.customtype) = "ecdsaPK"];
}
// PrivKey defines a secp256r1 ECDSA private key.
message PrivKey {
// secret number serialized using big-endian encoding
bytes secret = 1 [(gogoproto.customtype) = "ecdsaSK"];
}

View File

@ -0,0 +1,78 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.feegrant.v1beta1;
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/feegrant";
// BasicAllowance implements Allowance with a one-time grant of tokens
// that optionally expires. The grantee can use up to SpendLimit to cover fees.
message BasicAllowance {
option (cosmos_proto.implements_interface) = "FeeAllowanceI";
// spend_limit specifies the maximum amount of tokens that can be spent
// by this allowance and will be updated as tokens are spent. If it is
// empty, there is no spend limit and any amount of coins can be spent.
repeated cosmos.base.v1beta1.Coin spend_limit = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
// expiration specifies an optional time when this allowance expires
google.protobuf.Timestamp expiration = 2 [(gogoproto.stdtime) = true];
}
// PeriodicAllowance extends Allowance to allow for both a maximum cap,
// as well as a limit per time period.
message PeriodicAllowance {
option (cosmos_proto.implements_interface) = "FeeAllowanceI";
// basic specifies a struct of `BasicAllowance`
BasicAllowance basic = 1 [(gogoproto.nullable) = false];
// period specifies the time duration in which period_spend_limit coins can
// be spent before that allowance is reset
google.protobuf.Duration period = 2 [(gogoproto.stdduration) = true, (gogoproto.nullable) = false];
// period_spend_limit specifies the maximum number of coins that can be spent
// in the period
repeated cosmos.base.v1beta1.Coin period_spend_limit = 3
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
// period_can_spend is the number of coins left to be spent before the period_reset time
repeated cosmos.base.v1beta1.Coin period_can_spend = 4
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"];
// period_reset is the time at which this period resets and a new one begins,
// it is calculated from the start time of the first transaction after the
// last period ended
google.protobuf.Timestamp period_reset = 5 [(gogoproto.stdtime) = true, (gogoproto.nullable) = false];
}
// AllowedMsgAllowance creates allowance only for specified message types.
message AllowedMsgAllowance {
option (gogoproto.goproto_getters) = false;
option (cosmos_proto.implements_interface) = "FeeAllowanceI";
// allowance can be any of basic and filtered fee allowance.
google.protobuf.Any allowance = 1 [(cosmos_proto.accepts_interface) = "FeeAllowanceI"];
// allowed_messages are the messages for which the grantee has the access.
repeated string allowed_messages = 2;
}
// Grant is stored in the KVStore to record a grant with full context
message Grant {
// granter is the address of the user granting an allowance of their funds.
string granter = 1;
// grantee is the address of the user being granted an allowance of another user's funds.
string grantee = 2;
// allowance can be any of basic and filtered fee allowance.
google.protobuf.Any allowance = 3 [(cosmos_proto.accepts_interface) = "FeeAllowanceI"];
}

View File

@ -0,0 +1,13 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.feegrant.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos/feegrant/v1beta1/feegrant.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/feegrant";
// GenesisState contains a set of fee allowances, persisted from the store
message GenesisState {
repeated Grant allowances = 1 [(gogoproto.nullable) = false];
}

View File

@ -0,0 +1,55 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.feegrant.v1beta1;
import "cosmos/feegrant/v1beta1/feegrant.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "google/api/annotations.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/feegrant";
// Query defines the gRPC querier service.
service Query {
// Allowance returns fee granted to the grantee by the granter.
rpc Allowance(QueryAllowanceRequest) returns (QueryAllowanceResponse) {
option (google.api.http).get = "/cosmos/feegrant/v1beta1/allowance/{granter}/{grantee}";
}
// Allowances returns all the grants for address.
rpc Allowances(QueryAllowancesRequest) returns (QueryAllowancesResponse) {
option (google.api.http).get = "/cosmos/feegrant/v1beta1/allowances/{grantee}";
}
}
// QueryAllowanceRequest is the request type for the Query/Allowance RPC method.
message QueryAllowanceRequest {
// granter is the address of the user granting an allowance of their funds.
string granter = 1;
// grantee is the address of the user being granted an allowance of another user's funds.
string grantee = 2;
}
// QueryAllowanceResponse is the response type for the Query/Allowance RPC method.
message QueryAllowanceResponse {
// allowance is a allowance granted for grantee by granter.
cosmos.feegrant.v1beta1.Grant allowance = 1;
}
// QueryAllowancesRequest is the request type for the Query/Allowances RPC method.
message QueryAllowancesRequest {
string grantee = 1;
// pagination defines an pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 2;
}
// QueryAllowancesResponse is the response type for the Query/Allowances RPC method.
message QueryAllowancesResponse {
// allowances are allowance's granted for grantee by granter.
repeated cosmos.feegrant.v1beta1.Grant allowances = 1;
// pagination defines an pagination for the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}

View File

@ -0,0 +1,49 @@
// Since: cosmos-sdk 0.43
syntax = "proto3";
package cosmos.feegrant.v1beta1;
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "cosmos_proto/cosmos.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/feegrant";
// Msg defines the feegrant msg service.
service Msg {
// GrantAllowance grants fee allowance to the grantee on the granter's
// account with the provided expiration time.
rpc GrantAllowance(MsgGrantAllowance) returns (MsgGrantAllowanceResponse);
// RevokeAllowance revokes any fee allowance of granter's account that
// has been granted to the grantee.
rpc RevokeAllowance(MsgRevokeAllowance) returns (MsgRevokeAllowanceResponse);
}
// MsgGrantAllowance adds permission for Grantee to spend up to Allowance
// of fees from the account of Granter.
message MsgGrantAllowance {
// granter is the address of the user granting an allowance of their funds.
string granter = 1;
// grantee is the address of the user being granted an allowance of another user's funds.
string grantee = 2;
// allowance can be any of basic and filtered fee allowance.
google.protobuf.Any allowance = 3 [(cosmos_proto.accepts_interface) = "FeeAllowanceI"];
}
// MsgGrantAllowanceResponse defines the Msg/GrantAllowanceResponse response type.
message MsgGrantAllowanceResponse {}
// MsgRevokeAllowance removes any existing Allowance from Granter to Grantee.
message MsgRevokeAllowance {
// granter is the address of the user granting an allowance of their funds.
string granter = 1;
// grantee is the address of the user being granted an allowance of another user's funds.
string grantee = 2;
}
// MsgRevokeAllowanceResponse defines the Msg/RevokeAllowanceResponse response type.
message MsgRevokeAllowanceResponse {}

View File

@ -29,6 +29,18 @@ enum VoteOption {
VOTE_OPTION_NO_WITH_VETO = 4 [(gogoproto.enumvalue_customname) = "OptionNoWithVeto"];
}
// WeightedVoteOption defines a unit of vote for vote split.
//
// Since: cosmos-sdk 0.43
message WeightedVoteOption {
VoteOption option = 1;
string weight = 2 [
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec",
(gogoproto.nullable) = false,
(gogoproto.moretags) = "yaml:\"weight\""
];
}
// TextProposal defines a standard text proposal whose changes need to be
// manually updated in case of approval.
message TextProposal {
@ -119,9 +131,14 @@ message Vote {
option (gogoproto.goproto_stringer) = false;
option (gogoproto.equal) = false;
uint64 proposal_id = 1 [(gogoproto.moretags) = "yaml:\"proposal_id\""];
string voter = 2;
VoteOption option = 3;
uint64 proposal_id = 1 [(gogoproto.moretags) = "yaml:\"proposal_id\""];
string voter = 2;
// Deprecated: Prefer to use `options` instead. This field is set in queries
// if and only if `len(options) == 1` and that option has weight 1. In all
// other cases, this field will default to VOTE_OPTION_UNSPECIFIED.
VoteOption option = 3 [deprecated = true];
// Since: cosmos-sdk 0.43
repeated WeightedVoteOption options = 4 [(gogoproto.nullable) = false];
}
// DepositParams defines the params for deposits on governance proposals.

View File

@ -17,6 +17,11 @@ service Msg {
// Vote defines a method to add a vote on a specific proposal.
rpc Vote(MsgVote) returns (MsgVoteResponse);
// VoteWeighted defines a method to add a weighted vote on a specific proposal.
//
// Since: cosmos-sdk 0.43
rpc VoteWeighted(MsgVoteWeighted) returns (MsgVoteWeightedResponse);
// Deposit defines a method to add deposit on a specific proposal.
rpc Deposit(MsgDeposit) returns (MsgDepositResponse);
}
@ -58,6 +63,25 @@ message MsgVote {
// MsgVoteResponse defines the Msg/Vote response type.
message MsgVoteResponse {}
// MsgVoteWeighted defines a message to cast a vote.
//
// Since: cosmos-sdk 0.43
message MsgVoteWeighted {
option (gogoproto.equal) = false;
option (gogoproto.goproto_stringer) = false;
option (gogoproto.stringer) = false;
option (gogoproto.goproto_getters) = false;
uint64 proposal_id = 1 [(gogoproto.moretags) = "yaml:\"proposal_id\""];
string voter = 2;
repeated WeightedVoteOption options = 3 [(gogoproto.nullable) = false];
}
// MsgVoteWeightedResponse defines the Msg/VoteWeighted response type.
//
// Since: cosmos-sdk 0.43
message MsgVoteWeightedResponse {}
// MsgDeposit defines a message to submit a deposit to an existing proposal.
message MsgDeposit {
option (gogoproto.equal) = false;

View File

@ -16,7 +16,7 @@ message GenesisState {
repeated SigningInfo signing_infos = 2
[(gogoproto.moretags) = "yaml:\"signing_infos\"", (gogoproto.nullable) = false];
// signing_infos represents a map between validator addresses and their
// missed_blocks represents a map between validator addresses and their
// missed blocks.
repeated ValidatorMissedBlocks missed_blocks = 3
[(gogoproto.moretags) = "yaml:\"missed_blocks\"", (gogoproto.nullable) = false];

View File

@ -15,17 +15,20 @@ message ValidatorSigningInfo {
option (gogoproto.goproto_stringer) = false;
string address = 1;
// height at which validator was first a candidate OR was unjailed
// Height at which validator was first a candidate OR was unjailed
int64 start_height = 2 [(gogoproto.moretags) = "yaml:\"start_height\""];
// index offset into signed block bit array
// Index which is incremented each time the validator was a bonded
// in a block and may have signed a precommit or not. This in conjunction with the
// `SignedBlocksWindow` param determines the index in the `MissedBlocksBitArray`.
int64 index_offset = 3 [(gogoproto.moretags) = "yaml:\"index_offset\""];
// timestamp validator cannot be unjailed until
// Timestamp until which the validator is jailed due to liveness downtime.
google.protobuf.Timestamp jailed_until = 4
[(gogoproto.moretags) = "yaml:\"jailed_until\"", (gogoproto.stdtime) = true, (gogoproto.nullable) = false];
// whether or not a validator has been tombstoned (killed out of validator
// set)
// Whether or not a validator has been tombstoned (killed out of validator set). It is set
// once the validator commits an equivocation or for any other configured misbehiavor.
bool tombstoned = 5;
// missed blocks counter (to avoid scanning the array every time)
// A counter kept to avoid unnecessary array reads.
// Note that `Sum(MissedBlocksBitArray)` always equals `MissedBlocksCounter`.
int64 missed_blocks_counter = 6 [(gogoproto.moretags) = "yaml:\"missed_blocks_counter\""];
}

View File

@ -0,0 +1,47 @@
syntax = "proto3";
package cosmos.staking.v1beta1;
import "gogoproto/gogo.proto";
import "cosmos_proto/cosmos.proto";
import "cosmos/base/v1beta1/coin.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/staking/types";
// StakeAuthorization defines authorization for delegate/undelegate/redelegate.
//
// Since: cosmos-sdk 0.43
message StakeAuthorization {
option (cosmos_proto.implements_interface) = "Authorization";
// max_tokens specifies the maximum amount of tokens can be delegate to a validator. If it is
// empty, there is no spend limit and any amount of coins can be delegated.
cosmos.base.v1beta1.Coin max_tokens = 1 [(gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coin"];
// validators is the oneof that represents either allow_list or deny_list
oneof validators {
// allow_list specifies list of validator addresses to whom grantee can delegate tokens on behalf of granter's
// account.
Validators allow_list = 2;
// deny_list specifies list of validator addresses to whom grantee can not delegate tokens.
Validators deny_list = 3;
}
// Validators defines list of validator addresses.
message Validators {
repeated string address = 1;
}
// authorization_type defines one of AuthorizationType.
AuthorizationType authorization_type = 4;
}
// AuthorizationType defines the type of staking module authorization type
//
// Since: cosmos-sdk 0.43
enum AuthorizationType {
// AUTHORIZATION_TYPE_UNSPECIFIED specifies an unknown authorization type
AUTHORIZATION_TYPE_UNSPECIFIED = 0;
// AUTHORIZATION_TYPE_DELEGATE defines an authorization type for Msg/Delegate
AUTHORIZATION_TYPE_DELEGATE = 1;
// AUTHORIZATION_TYPE_UNDELEGATE defines an authorization type for Msg/Undelegate
AUTHORIZATION_TYPE_UNDELEGATE = 2;
// AUTHORIZATION_TYPE_REDELEGATE defines an authorization type for Msg/BeginRedelegate
AUTHORIZATION_TYPE_REDELEGATE = 3;
}

View File

@ -28,7 +28,7 @@ message CommissionRates {
option (gogoproto.goproto_stringer) = false;
// rate is the commission rate charged to delegators, as a fraction.
string rate = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false];
string rate = 1 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false];
// max_rate defines the maximum commission rate which validator can ever charge, as a fraction.
string max_rate = 2 [
(gogoproto.moretags) = "yaml:\"max_rate\"",
@ -49,9 +49,9 @@ message Commission {
option (gogoproto.goproto_stringer) = false;
// commission_rates defines the initial commission rates to be used for creating a validator.
CommissionRates commission_rates = 1 [(gogoproto.embed) = true, (gogoproto.nullable) = false];
CommissionRates commission_rates = 1 [(gogoproto.embed) = true, (gogoproto.nullable) = false];
// update_time is the last time the commission rate was changed.
google.protobuf.Timestamp update_time = 2
google.protobuf.Timestamp update_time = 2
[(gogoproto.nullable) = false, (gogoproto.stdtime) = true, (gogoproto.moretags) = "yaml:\"update_time\""];
}
@ -61,15 +61,15 @@ message Description {
option (gogoproto.goproto_stringer) = false;
// moniker defines a human-readable name for the validator.
string moniker = 1;
string moniker = 1;
// identity defines an optional identity signature (ex. UPort or Keybase).
string identity = 2;
string identity = 2;
// website defines an optional website link.
string website = 3;
string website = 3;
// security_contact defines an optional email for security contact.
string security_contact = 4 [(gogoproto.moretags) = "yaml:\"security_contact\""];
// details define other optional details.
string details = 5;
string details = 5;
}
// Validator defines a validator, together with the total amount of the
@ -86,12 +86,12 @@ message Validator {
option (gogoproto.goproto_getters) = false;
// operator_address defines the address of the validator's operator; bech encoded in JSON.
string operator_address = 1 [(gogoproto.moretags) = "yaml:\"operator_address\""];
string operator_address = 1 [(gogoproto.moretags) = "yaml:\"operator_address\""];
// consensus_pubkey is the consensus public key of the validator, as a Protobuf Any.
google.protobuf.Any consensus_pubkey = 2
[(cosmos_proto.accepts_interface) = "cosmos.crypto.PubKey", (gogoproto.moretags) = "yaml:\"consensus_pubkey\""];
// jailed defined whether the validator has been jailed from bonded status or not.
bool jailed = 3;
bool jailed = 3;
// status is the validator status (bonded/unbonding/unbonded).
BondStatus status = 4;
// tokens define the delegated tokens (incl. self-delegation).
@ -103,16 +103,16 @@ message Validator {
(gogoproto.nullable) = false
];
// description defines the description terms for the validator.
Description description = 7 [(gogoproto.nullable) = false];
Description description = 7 [(gogoproto.nullable) = false];
// unbonding_height defines, if unbonding, the height at which this validator has begun unbonding.
int64 unbonding_height = 8 [(gogoproto.moretags) = "yaml:\"unbonding_height\""];
int64 unbonding_height = 8 [(gogoproto.moretags) = "yaml:\"unbonding_height\""];
// unbonding_time defines, if unbonding, the min time for the validator to complete unbonding.
google.protobuf.Timestamp unbonding_time = 9
google.protobuf.Timestamp unbonding_time = 9
[(gogoproto.nullable) = false, (gogoproto.stdtime) = true, (gogoproto.moretags) = "yaml:\"unbonding_time\""];
// commission defines the commission parameters.
Commission commission = 10 [(gogoproto.nullable) = false];
Commission commission = 10 [(gogoproto.nullable) = false];
// min_self_delegation is the validator's self declared minimum self delegation.
string min_self_delegation = 11 [
string min_self_delegation = 11 [
(gogoproto.moretags) = "yaml:\"min_self_delegation\"",
(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int",
(gogoproto.nullable) = false
@ -201,9 +201,9 @@ message UnbondingDelegation {
option (gogoproto.goproto_stringer) = false;
// delegator_address is the bech32-encoded address of the delegator.
string delegator_address = 1 [(gogoproto.moretags) = "yaml:\"delegator_address\""];
string delegator_address = 1 [(gogoproto.moretags) = "yaml:\"delegator_address\""];
// validator_address is the bech32-encoded address of the validator.
string validator_address = 2 [(gogoproto.moretags) = "yaml:\"validator_address\""];
string validator_address = 2 [(gogoproto.moretags) = "yaml:\"validator_address\""];
// entries are the unbonding delegation entries.
repeated UnbondingDelegationEntry entries = 3 [(gogoproto.nullable) = false]; // unbonding delegation entries
}
@ -214,7 +214,7 @@ message UnbondingDelegationEntry {
option (gogoproto.goproto_stringer) = false;
// creation_height is the height which the unbonding took place.
int64 creation_height = 1 [(gogoproto.moretags) = "yaml:\"creation_height\""];
int64 creation_height = 1 [(gogoproto.moretags) = "yaml:\"creation_height\""];
// completion_time is the unix time for unbonding completion.
google.protobuf.Timestamp completion_time = 2
[(gogoproto.nullable) = false, (gogoproto.stdtime) = true, (gogoproto.moretags) = "yaml:\"completion_time\""];
@ -234,7 +234,7 @@ message RedelegationEntry {
option (gogoproto.goproto_stringer) = false;
// creation_height defines the height which the redelegation took place.
int64 creation_height = 1 [(gogoproto.moretags) = "yaml:\"creation_height\""];
int64 creation_height = 1 [(gogoproto.moretags) = "yaml:\"creation_height\""];
// completion_time defines the unix time for redelegation completion.
google.protobuf.Timestamp completion_time = 2
[(gogoproto.nullable) = false, (gogoproto.stdtime) = true, (gogoproto.moretags) = "yaml:\"completion_time\""];
@ -257,13 +257,13 @@ message Redelegation {
option (gogoproto.goproto_stringer) = false;
// delegator_address is the bech32-encoded address of the delegator.
string delegator_address = 1 [(gogoproto.moretags) = "yaml:\"delegator_address\""];
string delegator_address = 1 [(gogoproto.moretags) = "yaml:\"delegator_address\""];
// validator_src_address is the validator redelegation source operator address.
string validator_src_address = 2 [(gogoproto.moretags) = "yaml:\"validator_src_address\""];
string validator_src_address = 2 [(gogoproto.moretags) = "yaml:\"validator_src_address\""];
// validator_dst_address is the validator redelegation destination operator address.
string validator_dst_address = 3 [(gogoproto.moretags) = "yaml:\"validator_dst_address\""];
string validator_dst_address = 3 [(gogoproto.moretags) = "yaml:\"validator_dst_address\""];
// entries are the redelegation entries.
repeated RedelegationEntry entries = 4 [(gogoproto.nullable) = false]; // redelegation entries
repeated RedelegationEntry entries = 4 [(gogoproto.nullable) = false]; // redelegation entries
}
// Params defines the parameters for the staking module.
@ -275,13 +275,13 @@ message Params {
google.protobuf.Duration unbonding_time = 1
[(gogoproto.nullable) = false, (gogoproto.stdduration) = true, (gogoproto.moretags) = "yaml:\"unbonding_time\""];
// max_validators is the maximum number of validators.
uint32 max_validators = 2 [(gogoproto.moretags) = "yaml:\"max_validators\""];
uint32 max_validators = 2 [(gogoproto.moretags) = "yaml:\"max_validators\""];
// max_entries is the max entries for either unbonding delegation or redelegation (per pair/trio).
uint32 max_entries = 3 [(gogoproto.moretags) = "yaml:\"max_entries\""];
uint32 max_entries = 3 [(gogoproto.moretags) = "yaml:\"max_entries\""];
// historical_entries is the number of historical entries to persist.
uint32 historical_entries = 4 [(gogoproto.moretags) = "yaml:\"historical_entries\""];
// bond_denom defines the bondable coin denomination.
string bond_denom = 5 [(gogoproto.moretags) = "yaml:\"bond_denom\""];
string bond_denom = 5 [(gogoproto.moretags) = "yaml:\"bond_denom\""];
}
// DelegationResponse is equivalent to Delegation except that it contains a

View File

@ -7,7 +7,8 @@ import "cosmos/tx/v1beta1/tx.proto";
import "gogoproto/gogo.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
option go_package = "github.com/cosmos/cosmos-sdk/types/tx";
option (gogoproto.goproto_registration) = true;
option go_package = "github.com/cosmos/cosmos-sdk/types/tx";
// Service defines a gRPC service for interacting with transactions.
service Service {
@ -42,6 +43,17 @@ message GetTxsEventRequest {
repeated string events = 1;
// pagination defines an pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 2;
OrderBy order_by = 3;
}
// OrderBy defines the sorting order
enum OrderBy {
// ORDER_BY_UNSPECIFIED specifies an unknown sorting order. OrderBy defaults to ASC in this case.
ORDER_BY_UNSPECIFIED = 0;
// ORDER_BY_ASC defines ascending order
ORDER_BY_ASC = 1;
// ORDER_BY_DESC defines descending order
ORDER_BY_DESC = 2;
}
// GetTxsEventResponse is the response type for the Service.TxsByEvents
@ -89,7 +101,12 @@ message BroadcastTxResponse {
// RPC method.
message SimulateRequest {
// tx is the transaction to simulate.
cosmos.tx.v1beta1.Tx tx = 1;
// Deprecated. Send raw tx bytes instead.
cosmos.tx.v1beta1.Tx tx = 1 [deprecated = true];
// tx_bytes is the raw transaction.
//
// Since: cosmos-sdk 0.43
bytes tx_bytes = 2;
}
// SimulateResponse is the response type for the

View File

@ -74,7 +74,9 @@ message TxBody {
// transaction.
repeated google.protobuf.Any messages = 1;
// memo is any arbitrary memo to be added to the transaction
// memo is any arbitrary note/comment to be added to the transaction.
// WARNING: in clients, any publicly exposed text should not be called memo,
// but should be called `note` instead (see https://github.com/cosmos/cosmos-sdk/issues/9122).
string memo = 2;
// timeout is the block height after which this transaction will not

View File

@ -23,9 +23,19 @@ service Query {
// as a trusted kernel for the next version of this chain. It will only be
// stored at the last height of this chain.
// UpgradedConsensusState RPC not supported with legacy querier
// This rpc is deprecated now that IBC has its own replacement
// (https://github.com/cosmos/ibc-go/blob/2c880a22e9f9cc75f62b527ca94aa75ce1106001/proto/ibc/core/client/v1/query.proto#L54)
rpc UpgradedConsensusState(QueryUpgradedConsensusStateRequest) returns (QueryUpgradedConsensusStateResponse) {
option deprecated = true;
option (google.api.http).get = "/cosmos/upgrade/v1beta1/upgraded_consensus_state/{last_height}";
}
// ModuleVersions queries the list of module versions from state.
//
// Since: cosmos-sdk 0.43
rpc ModuleVersions(QueryModuleVersionsRequest) returns (QueryModuleVersionsResponse) {
option (google.api.http).get = "/cosmos/upgrade/v1beta1/module_versions";
}
}
// QueryCurrentPlanRequest is the request type for the Query/CurrentPlan RPC
@ -56,6 +66,8 @@ message QueryAppliedPlanResponse {
// QueryUpgradedConsensusStateRequest is the request type for the Query/UpgradedConsensusState
// RPC method.
message QueryUpgradedConsensusStateRequest {
option deprecated = true;
// last height of the current chain must be sent in request
// as this is the height under which next consensus state is stored
int64 last_height = 1;
@ -64,5 +76,29 @@ message QueryUpgradedConsensusStateRequest {
// QueryUpgradedConsensusStateResponse is the response type for the Query/UpgradedConsensusState
// RPC method.
message QueryUpgradedConsensusStateResponse {
google.protobuf.Any upgraded_consensus_state = 1;
option deprecated = true;
reserved 1;
// Since: cosmos-sdk 0.43
bytes upgraded_consensus_state = 2;
}
// QueryModuleVersionsRequest is the request type for the Query/ModuleVersions
// RPC method.
//
// Since: cosmos-sdk 0.43
message QueryModuleVersionsRequest {
// module_name is a field to query a specific module
// consensus version from state. Leaving this empty will
// fetch the full list of module versions from state
string module_name = 1;
}
// QueryModuleVersionsResponse is the response type for the Query/ModuleVersions
// RPC method.
//
// Since: cosmos-sdk 0.43
message QueryModuleVersionsResponse {
// module_versions is a list of module names with their consensus versions.
repeated ModuleVersion module_versions = 1;
}

View File

@ -5,13 +5,13 @@ import "google/protobuf/any.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/upgrade/types";
option (gogoproto.goproto_stringer_all) = false;
option (gogoproto.goproto_getters_all) = false;
option go_package = "github.com/cosmos/cosmos-sdk/x/upgrade/types";
option (gogoproto.goproto_getters_all) = false;
// Plan specifies information about a planned upgrade and when it should occur.
message Plan {
option (gogoproto.equal) = true;
option (gogoproto.equal) = true;
option (gogoproto.goproto_stringer) = false;
// Sets the name for the upgrade. This name will be used by the upgraded
// version of the software to apply any special "on-upgrade" commands during
@ -22,9 +22,10 @@ message Plan {
// reached and the software will exit.
string name = 1;
// The time after which the upgrade must be performed.
// Leave set to its zero value to use a pre-defined Height instead.
google.protobuf.Timestamp time = 2 [(gogoproto.stdtime) = true, (gogoproto.nullable) = false];
// Deprecated: Time based upgrades have been deprecated. Time based upgrade logic
// has been removed from the SDK.
// If this field is not empty, an error will be thrown.
google.protobuf.Timestamp time = 2 [deprecated = true, (gogoproto.stdtime) = true, (gogoproto.nullable) = false];
// The height at which the upgrade must be performed.
// Only used if Time is not set.
@ -34,18 +35,18 @@ message Plan {
// such as a git commit that validators could automatically upgrade to
string info = 4;
// IBC-enabled chains can opt-in to including the upgraded client state in its upgrade plan
// This will make the chain commit to the correct upgraded (self) client state before the upgrade occurs,
// so that connecting chains can verify that the new upgraded client is valid by verifying a proof on the
// previous version of the chain.
// This will allow IBC connections to persist smoothly across planned chain upgrades
google.protobuf.Any upgraded_client_state = 5 [(gogoproto.moretags) = "yaml:\"upgraded_client_state\""];
// Deprecated: UpgradedClientState field has been deprecated. IBC upgrade logic has been
// moved to the IBC module in the sub module 02-client.
// If this field is not empty, an error will be thrown.
google.protobuf.Any upgraded_client_state = 5
[deprecated = true, (gogoproto.moretags) = "yaml:\"upgraded_client_state\""];
}
// SoftwareUpgradeProposal is a gov Content type for initiating a software
// upgrade.
message SoftwareUpgradeProposal {
option (gogoproto.equal) = true;
option (gogoproto.equal) = true;
option (gogoproto.goproto_stringer) = false;
string title = 1;
string description = 2;
@ -55,8 +56,23 @@ message SoftwareUpgradeProposal {
// CancelSoftwareUpgradeProposal is a gov Content type for cancelling a software
// upgrade.
message CancelSoftwareUpgradeProposal {
option (gogoproto.equal) = true;
option (gogoproto.equal) = true;
option (gogoproto.goproto_stringer) = false;
string title = 1;
string description = 2;
}
// ModuleVersion specifies a module and its consensus version.
//
// Since: cosmos-sdk 0.43
message ModuleVersion {
option (gogoproto.equal) = true;
option (gogoproto.goproto_stringer) = true;
// name of the app module
string name = 1;
// consensus version of the app module
uint64 version = 2;
}

View File

@ -71,3 +71,15 @@ message PeriodicVestingAccount {
int64 start_time = 2 [(gogoproto.moretags) = "yaml:\"start_time\""];
repeated Period vesting_periods = 3 [(gogoproto.moretags) = "yaml:\"vesting_periods\"", (gogoproto.nullable) = false];
}
// PermanentLockedAccount implements the VestingAccount interface. It does
// not ever release coins, locking them indefinitely. Coins in this account can
// still be used for delegating and for governance votes even while locked.
//
// Since: cosmos-sdk 0.43
message PermanentLockedAccount {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
BaseVestingAccount base_vesting_account = 1 [(gogoproto.embed) = true];
}

View File

@ -156,6 +156,9 @@ message Any {
bytes value = 2;
option (gogoproto.typedecl) = false;
option (gogoproto.goproto_stringer) = false;
option (gogoproto.gostring) = false;
option (gogoproto.stringer) = false;
}
option (gogoproto.goproto_registration) = false;

View File

@ -1,18 +0,0 @@
syntax = "proto3";
package ibc.applications.transfer.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types";
import "gogoproto/gogo.proto";
import "ibc/applications/transfer/v1/transfer.proto";
// GenesisState defines the ibc-transfer genesis state
message GenesisState {
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
repeated DenomTrace denom_traces = 2 [
(gogoproto.castrepeated) = "Traces",
(gogoproto.nullable) = false,
(gogoproto.moretags) = "yaml:\"denom_traces\""
];
Params params = 3 [(gogoproto.nullable) = false];
}

View File

@ -1,66 +0,0 @@
syntax = "proto3";
package ibc.applications.transfer.v1;
import "gogoproto/gogo.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "ibc/applications/transfer/v1/transfer.proto";
import "google/api/annotations.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types";
// Query provides defines the gRPC querier service.
service Query {
// DenomTrace queries a denomination trace information.
rpc DenomTrace(QueryDenomTraceRequest) returns (QueryDenomTraceResponse) {
option (google.api.http).get = "/ibc/applications/transfer/v1beta1/denom_traces/{hash}";
}
// DenomTraces queries all denomination traces.
rpc DenomTraces(QueryDenomTracesRequest) returns (QueryDenomTracesResponse) {
option (google.api.http).get = "/ibc/applications/transfer/v1beta1/denom_traces";
}
// Params queries all parameters of the ibc-transfer module.
rpc Params(QueryParamsRequest) returns (QueryParamsResponse) {
option (google.api.http).get = "/ibc/applications/transfer/v1beta1/params";
}
}
// QueryDenomTraceRequest is the request type for the Query/DenomTrace RPC
// method
message QueryDenomTraceRequest {
// hash (in hex format) of the denomination trace information.
string hash = 1;
}
// QueryDenomTraceResponse is the response type for the Query/DenomTrace RPC
// method.
message QueryDenomTraceResponse {
// denom_trace returns the requested denomination trace information.
DenomTrace denom_trace = 1;
}
// QueryConnectionsRequest is the request type for the Query/DenomTraces RPC
// method
message QueryDenomTracesRequest {
// pagination defines an optional pagination for the request.
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryConnectionsResponse is the response type for the Query/DenomTraces RPC
// method.
message QueryDenomTracesResponse {
// denom_traces returns all denominations trace information.
repeated DenomTrace denom_traces = 1 [(gogoproto.castrepeated) = "Traces", (gogoproto.nullable) = false];
// pagination defines the pagination in the response.
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
// QueryParamsRequest is the request type for the Query/Params RPC method.
message QueryParamsRequest {}
// QueryParamsResponse is the response type for the Query/Params RPC method.
message QueryParamsResponse {
// params defines the parameters of the module.
Params params = 1;
}

View File

@ -1,43 +0,0 @@
syntax = "proto3";
package ibc.applications.transfer.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types";
import "gogoproto/gogo.proto";
// FungibleTokenPacketData defines a struct for the packet payload
// See FungibleTokenPacketData spec:
// https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#data-structures
message FungibleTokenPacketData {
// the token denomination to be transferred
string denom = 1;
// the token amount to be transferred
uint64 amount = 2;
// the sender address
string sender = 3;
// the recipient address on the destination chain
string receiver = 4;
}
// DenomTrace contains the base denomination for ICS20 fungible tokens and the
// source tracing information path.
message DenomTrace {
// path defines the chain of port/channel identifiers used for tracing the
// source of the fungible token.
string path = 1;
// base denomination of the relayed fungible token.
string base_denom = 2;
}
// Params defines the set of IBC transfer parameters.
// NOTE: To prevent a single token from being transferred, set the
// TransfersEnabled parameter to true and then set the bank module's SendEnabled
// parameter for the denomination to false.
message Params {
// send_enabled enables or disables all cross-chain token transfers from this
// chain.
bool send_enabled = 1 [(gogoproto.moretags) = "yaml:\"send_enabled\""];
// receive_enabled enables or disables all cross-chain token transfers to this
// chain.
bool receive_enabled = 2 [(gogoproto.moretags) = "yaml:\"receive_enabled\""];
}

View File

@ -1,43 +0,0 @@
syntax = "proto3";
package ibc.applications.transfer.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types";
import "gogoproto/gogo.proto";
import "cosmos/base/v1beta1/coin.proto";
import "ibc/core/client/v1/client.proto";
// Msg defines the ibc/transfer Msg service.
service Msg {
// Transfer defines a rpc handler method for MsgTransfer.
rpc Transfer(MsgTransfer) returns (MsgTransferResponse);
}
// MsgTransfer defines a msg to transfer fungible tokens (i.e Coins) between
// ICS20 enabled chains. See ICS Spec here:
// https://github.com/cosmos/ics/tree/master/spec/ics-020-fungible-token-transfer#data-structures
message MsgTransfer {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// the port on which the packet will be sent
string source_port = 1 [(gogoproto.moretags) = "yaml:\"source_port\""];
// the channel by which the packet will be sent
string source_channel = 2 [(gogoproto.moretags) = "yaml:\"source_channel\""];
// the tokens to be transferred
cosmos.base.v1beta1.Coin token = 3 [(gogoproto.nullable) = false];
// the sender address
string sender = 4;
// the recipient address on the destination chain
string receiver = 5;
// Timeout height relative to the current block height.
// The timeout is disabled when set to 0.
ibc.core.client.v1.Height timeout_height = 6
[(gogoproto.moretags) = "yaml:\"timeout_height\"", (gogoproto.nullable) = false];
// Timeout timestamp (in nanoseconds) relative to the current block timestamp.
// The timeout is disabled when set to 0.
uint64 timeout_timestamp = 7 [(gogoproto.moretags) = "yaml:\"timeout_timestamp\""];
}
// MsgTransferResponse defines the Msg/Transfer response type.
message MsgTransferResponse {}

View File

@ -1,147 +0,0 @@
syntax = "proto3";
package ibc.core.channel.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types";
import "gogoproto/gogo.proto";
import "ibc/core/client/v1/client.proto";
// Channel defines pipeline for exactly-once packet delivery between specific
// modules on separate blockchains, which has at least one end capable of
// sending packets and one end capable of receiving packets.
message Channel {
option (gogoproto.goproto_getters) = false;
// current state of the channel end
State state = 1;
// whether the channel is ordered or unordered
Order ordering = 2;
// counterparty channel end
Counterparty counterparty = 3 [(gogoproto.nullable) = false];
// list of connection identifiers, in order, along which packets sent on
// this channel will travel
repeated string connection_hops = 4 [(gogoproto.moretags) = "yaml:\"connection_hops\""];
// opaque channel version, which is agreed upon during the handshake
string version = 5;
}
// IdentifiedChannel defines a channel with additional port and channel
// identifier fields.
message IdentifiedChannel {
option (gogoproto.goproto_getters) = false;
// current state of the channel end
State state = 1;
// whether the channel is ordered or unordered
Order ordering = 2;
// counterparty channel end
Counterparty counterparty = 3 [(gogoproto.nullable) = false];
// list of connection identifiers, in order, along which packets sent on
// this channel will travel
repeated string connection_hops = 4 [(gogoproto.moretags) = "yaml:\"connection_hops\""];
// opaque channel version, which is agreed upon during the handshake
string version = 5;
// port identifier
string port_id = 6;
// channel identifier
string channel_id = 7;
}
// State defines if a channel is in one of the following states:
// CLOSED, INIT, TRYOPEN, OPEN or UNINITIALIZED.
enum State {
option (gogoproto.goproto_enum_prefix) = false;
// Default State
STATE_UNINITIALIZED_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "UNINITIALIZED"];
// A channel has just started the opening handshake.
STATE_INIT = 1 [(gogoproto.enumvalue_customname) = "INIT"];
// A channel has acknowledged the handshake step on the counterparty chain.
STATE_TRYOPEN = 2 [(gogoproto.enumvalue_customname) = "TRYOPEN"];
// A channel has completed the handshake. Open channels are
// ready to send and receive packets.
STATE_OPEN = 3 [(gogoproto.enumvalue_customname) = "OPEN"];
// A channel has been closed and can no longer be used to send or receive
// packets.
STATE_CLOSED = 4 [(gogoproto.enumvalue_customname) = "CLOSED"];
}
// Order defines if a channel is ORDERED or UNORDERED
enum Order {
option (gogoproto.goproto_enum_prefix) = false;
// zero-value for channel ordering
ORDER_NONE_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "NONE"];
// packets can be delivered in any order, which may differ from the order in
// which they were sent.
ORDER_UNORDERED = 1 [(gogoproto.enumvalue_customname) = "UNORDERED"];
// packets are delivered exactly in the order which they were sent
ORDER_ORDERED = 2 [(gogoproto.enumvalue_customname) = "ORDERED"];
}
// Counterparty defines a channel end counterparty
message Counterparty {
option (gogoproto.goproto_getters) = false;
// port on the counterparty chain which owns the other end of the channel.
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
// channel end on the counterparty chain
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
}
// Packet defines a type that carries data across different chains through IBC
message Packet {
option (gogoproto.goproto_getters) = false;
// number corresponds to the order of sends and receives, where a Packet
// with an earlier sequence number must be sent and received before a Packet
// with a later sequence number.
uint64 sequence = 1;
// identifies the port on the sending chain.
string source_port = 2 [(gogoproto.moretags) = "yaml:\"source_port\""];
// identifies the channel end on the sending chain.
string source_channel = 3 [(gogoproto.moretags) = "yaml:\"source_channel\""];
// identifies the port on the receiving chain.
string destination_port = 4 [(gogoproto.moretags) = "yaml:\"destination_port\""];
// identifies the channel end on the receiving chain.
string destination_channel = 5 [(gogoproto.moretags) = "yaml:\"destination_channel\""];
// actual opaque bytes transferred directly to the application module
bytes data = 6;
// block height after which the packet times out
ibc.core.client.v1.Height timeout_height = 7
[(gogoproto.moretags) = "yaml:\"timeout_height\"", (gogoproto.nullable) = false];
// block timestamp (in nanoseconds) after which the packet times out
uint64 timeout_timestamp = 8 [(gogoproto.moretags) = "yaml:\"timeout_timestamp\""];
}
// PacketState defines the generic type necessary to retrieve and store
// packet commitments, acknowledgements, and receipts.
// Caller is responsible for knowing the context necessary to interpret this
// state as a commitment, acknowledgement, or a receipt.
message PacketState {
option (gogoproto.goproto_getters) = false;
// channel port identifier.
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
// channel unique identifier.
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
// packet sequence.
uint64 sequence = 3;
// embedded data that represents packet state.
bytes data = 4;
}
// Acknowledgement is the recommended acknowledgement format to be used by
// app-specific protocols.
// NOTE: The field numbers 21 and 22 were explicitly chosen to avoid accidental
// conflicts with other protobuf message formats used for acknowledgements.
// The first byte of any message with this format will be the non-ASCII values
// `0xaa` (result) or `0xb2` (error). Implemented as defined by ICS:
// https://github.com/cosmos/ics/tree/master/spec/ics-004-channel-and-packet-semantics#acknowledgement-envelope
message Acknowledgement {
// response contains either a result or an error and must be non-empty
oneof response {
bytes result = 21;
string error = 22;
}
}

View File

@ -1,31 +0,0 @@
syntax = "proto3";
package ibc.core.channel.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types";
import "gogoproto/gogo.proto";
import "ibc/core/channel/v1/channel.proto";
// GenesisState defines the ibc channel submodule's genesis state.
message GenesisState {
repeated IdentifiedChannel channels = 1 [(gogoproto.casttype) = "IdentifiedChannel", (gogoproto.nullable) = false];
repeated PacketState acknowledgements = 2 [(gogoproto.nullable) = false];
repeated PacketState commitments = 3 [(gogoproto.nullable) = false];
repeated PacketState receipts = 4 [(gogoproto.nullable) = false];
repeated PacketSequence send_sequences = 5
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"send_sequences\""];
repeated PacketSequence recv_sequences = 6
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"recv_sequences\""];
repeated PacketSequence ack_sequences = 7
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"ack_sequences\""];
// the sequence for the next generated channel identifier
uint64 next_channel_sequence = 8 [(gogoproto.moretags) = "yaml:\"next_channel_sequence\""];
}
// PacketSequence defines the genesis type necessary to retrieve and store
// next send and receive sequences.
message PacketSequence {
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
uint64 sequence = 3;
}

View File

@ -1,367 +0,0 @@
syntax = "proto3";
package ibc.core.channel.v1;
import "ibc/core/client/v1/client.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "ibc/core/channel/v1/channel.proto";
import "google/api/annotations.proto";
import "google/protobuf/any.proto";
import "gogoproto/gogo.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types";
// Query provides defines the gRPC querier service
service Query {
// Channel queries an IBC Channel.
rpc Channel(QueryChannelRequest) returns (QueryChannelResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}";
}
// Channels queries all the IBC channels of a chain.
rpc Channels(QueryChannelsRequest) returns (QueryChannelsResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels";
}
// ConnectionChannels queries all the channels associated with a connection
// end.
rpc ConnectionChannels(QueryConnectionChannelsRequest) returns (QueryConnectionChannelsResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/connections/{connection}/channels";
}
// ChannelClientState queries for the client state for the channel associated
// with the provided channel identifiers.
rpc ChannelClientState(QueryChannelClientStateRequest) returns (QueryChannelClientStateResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/client_state";
}
// ChannelConsensusState queries for the consensus state for the channel
// associated with the provided channel identifiers.
rpc ChannelConsensusState(QueryChannelConsensusStateRequest) returns (QueryChannelConsensusStateResponse) {
option (google.api.http).get =
"/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/consensus_state/revision/"
"{revision_number}/height/{revision_height}";
}
// PacketCommitment queries a stored packet commitment hash.
rpc PacketCommitment(QueryPacketCommitmentRequest) returns (QueryPacketCommitmentResponse) {
option (google.api.http).get =
"/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_commitments/{sequence}";
}
// PacketCommitments returns all the packet commitments hashes associated
// with a channel.
rpc PacketCommitments(QueryPacketCommitmentsRequest) returns (QueryPacketCommitmentsResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_commitments";
}
// PacketReceipt queries if a given packet sequence has been received on the queried chain
rpc PacketReceipt(QueryPacketReceiptRequest) returns (QueryPacketReceiptResponse) {
option (google.api.http).get =
"/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_receipts/{sequence}";
}
// PacketAcknowledgement queries a stored packet acknowledgement hash.
rpc PacketAcknowledgement(QueryPacketAcknowledgementRequest) returns (QueryPacketAcknowledgementResponse) {
option (google.api.http).get =
"/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_acks/{sequence}";
}
// PacketAcknowledgements returns all the packet acknowledgements associated
// with a channel.
rpc PacketAcknowledgements(QueryPacketAcknowledgementsRequest) returns (QueryPacketAcknowledgementsResponse) {
option (google.api.http).get =
"/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_acknowledgements";
}
// UnreceivedPackets returns all the unreceived IBC packets associated with a
// channel and sequences.
rpc UnreceivedPackets(QueryUnreceivedPacketsRequest) returns (QueryUnreceivedPacketsResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_commitments/"
"{packet_commitment_sequences}/unreceived_packets";
}
// UnreceivedAcks returns all the unreceived IBC acknowledgements associated with a
// channel and sequences.
rpc UnreceivedAcks(QueryUnreceivedAcksRequest) returns (QueryUnreceivedAcksResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/packet_commitments/"
"{packet_ack_sequences}/unreceived_acks";
}
// NextSequenceReceive returns the next receive sequence for a given channel.
rpc NextSequenceReceive(QueryNextSequenceReceiveRequest) returns (QueryNextSequenceReceiveResponse) {
option (google.api.http).get = "/ibc/core/channel/v1beta1/channels/{channel_id}/ports/{port_id}/next_sequence";
}
}
// QueryChannelRequest is the request type for the Query/Channel RPC method
message QueryChannelRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
}
// QueryChannelResponse is the response type for the Query/Channel RPC method.
// Besides the Channel end, it includes a proof and the height from which the
// proof was retrieved.
message QueryChannelResponse {
// channel associated with the request identifiers
ibc.core.channel.v1.Channel channel = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryChannelsRequest is the request type for the Query/Channels RPC method
message QueryChannelsRequest {
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryChannelsResponse is the response type for the Query/Channels RPC method.
message QueryChannelsResponse {
// list of stored channels of the chain.
repeated ibc.core.channel.v1.IdentifiedChannel channels = 1;
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
// query block height
ibc.core.client.v1.Height height = 3 [(gogoproto.nullable) = false];
}
// QueryConnectionChannelsRequest is the request type for the
// Query/QueryConnectionChannels RPC method
message QueryConnectionChannelsRequest {
// connection unique identifier
string connection = 1;
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 2;
}
// QueryConnectionChannelsResponse is the Response type for the
// Query/QueryConnectionChannels RPC method
message QueryConnectionChannelsResponse {
// list of channels associated with a connection.
repeated ibc.core.channel.v1.IdentifiedChannel channels = 1;
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
// query block height
ibc.core.client.v1.Height height = 3 [(gogoproto.nullable) = false];
}
// QueryChannelClientStateRequest is the request type for the Query/ClientState
// RPC method
message QueryChannelClientStateRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
}
// QueryChannelClientStateResponse is the Response type for the
// Query/QueryChannelClientState RPC method
message QueryChannelClientStateResponse {
// client state associated with the channel
ibc.core.client.v1.IdentifiedClientState identified_client_state = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryChannelConsensusStateRequest is the request type for the
// Query/ConsensusState RPC method
message QueryChannelConsensusStateRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// revision number of the consensus state
uint64 revision_number = 3;
// revision height of the consensus state
uint64 revision_height = 4;
}
// QueryChannelClientStateResponse is the Response type for the
// Query/QueryChannelClientState RPC method
message QueryChannelConsensusStateResponse {
// consensus state associated with the channel
google.protobuf.Any consensus_state = 1;
// client ID associated with the consensus state
string client_id = 2;
// merkle proof of existence
bytes proof = 3;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 4 [(gogoproto.nullable) = false];
}
// QueryPacketCommitmentRequest is the request type for the
// Query/PacketCommitment RPC method
message QueryPacketCommitmentRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// packet sequence
uint64 sequence = 3;
}
// QueryPacketCommitmentResponse defines the client query response for a packet
// which also includes a proof and the height from which the proof was
// retrieved
message QueryPacketCommitmentResponse {
// packet associated with the request fields
bytes commitment = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryPacketCommitmentsRequest is the request type for the
// Query/QueryPacketCommitments RPC method
message QueryPacketCommitmentsRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 3;
}
// QueryPacketCommitmentsResponse is the request type for the
// Query/QueryPacketCommitments RPC method
message QueryPacketCommitmentsResponse {
repeated ibc.core.channel.v1.PacketState commitments = 1;
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
// query block height
ibc.core.client.v1.Height height = 3 [(gogoproto.nullable) = false];
}
// QueryPacketReceiptRequest is the request type for the
// Query/PacketReceipt RPC method
message QueryPacketReceiptRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// packet sequence
uint64 sequence = 3;
}
// QueryPacketReceiptResponse defines the client query response for a packet receipt
// which also includes a proof, and the height from which the proof was
// retrieved
message QueryPacketReceiptResponse {
// success flag for if receipt exists
bool received = 2;
// merkle proof of existence
bytes proof = 3;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 4 [(gogoproto.nullable) = false];
}
// QueryPacketAcknowledgementRequest is the request type for the
// Query/PacketAcknowledgement RPC method
message QueryPacketAcknowledgementRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// packet sequence
uint64 sequence = 3;
}
// QueryPacketAcknowledgementResponse defines the client query response for a
// packet which also includes a proof and the height from which the
// proof was retrieved
message QueryPacketAcknowledgementResponse {
// packet associated with the request fields
bytes acknowledgement = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryPacketAcknowledgementsRequest is the request type for the
// Query/QueryPacketCommitments RPC method
message QueryPacketAcknowledgementsRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 3;
}
// QueryPacketAcknowledgemetsResponse is the request type for the
// Query/QueryPacketAcknowledgements RPC method
message QueryPacketAcknowledgementsResponse {
repeated ibc.core.channel.v1.PacketState acknowledgements = 1;
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
// query block height
ibc.core.client.v1.Height height = 3 [(gogoproto.nullable) = false];
}
// QueryUnreceivedPacketsRequest is the request type for the
// Query/UnreceivedPackets RPC method
message QueryUnreceivedPacketsRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// list of packet sequences
repeated uint64 packet_commitment_sequences = 3;
}
// QueryUnreceivedPacketsResponse is the response type for the
// Query/UnreceivedPacketCommitments RPC method
message QueryUnreceivedPacketsResponse {
// list of unreceived packet sequences
repeated uint64 sequences = 1;
// query block height
ibc.core.client.v1.Height height = 2 [(gogoproto.nullable) = false];
}
// QueryUnreceivedAcks is the request type for the
// Query/UnreceivedAcks RPC method
message QueryUnreceivedAcksRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
// list of acknowledgement sequences
repeated uint64 packet_ack_sequences = 3;
}
// QueryUnreceivedAcksResponse is the response type for the
// Query/UnreceivedAcks RPC method
message QueryUnreceivedAcksResponse {
// list of unreceived acknowledgement sequences
repeated uint64 sequences = 1;
// query block height
ibc.core.client.v1.Height height = 2 [(gogoproto.nullable) = false];
}
// QueryNextSequenceReceiveRequest is the request type for the
// Query/QueryNextSequenceReceiveRequest RPC method
message QueryNextSequenceReceiveRequest {
// port unique identifier
string port_id = 1;
// channel unique identifier
string channel_id = 2;
}
// QuerySequenceResponse is the request type for the
// Query/QueryNextSequenceReceiveResponse RPC method
message QueryNextSequenceReceiveResponse {
// next sequence receive number
uint64 next_sequence_receive = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}

View File

@ -1,207 +0,0 @@
syntax = "proto3";
package ibc.core.channel.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types";
import "gogoproto/gogo.proto";
import "ibc/core/client/v1/client.proto";
import "ibc/core/channel/v1/channel.proto";
// Msg defines the ibc/channel Msg service.
service Msg {
// ChannelOpenInit defines a rpc handler method for MsgChannelOpenInit.
rpc ChannelOpenInit(MsgChannelOpenInit) returns (MsgChannelOpenInitResponse);
// ChannelOpenTry defines a rpc handler method for MsgChannelOpenTry.
rpc ChannelOpenTry(MsgChannelOpenTry) returns (MsgChannelOpenTryResponse);
// ChannelOpenAck defines a rpc handler method for MsgChannelOpenAck.
rpc ChannelOpenAck(MsgChannelOpenAck) returns (MsgChannelOpenAckResponse);
// ChannelOpenConfirm defines a rpc handler method for MsgChannelOpenConfirm.
rpc ChannelOpenConfirm(MsgChannelOpenConfirm) returns (MsgChannelOpenConfirmResponse);
// ChannelCloseInit defines a rpc handler method for MsgChannelCloseInit.
rpc ChannelCloseInit(MsgChannelCloseInit) returns (MsgChannelCloseInitResponse);
// ChannelCloseConfirm defines a rpc handler method for MsgChannelCloseConfirm.
rpc ChannelCloseConfirm(MsgChannelCloseConfirm) returns (MsgChannelCloseConfirmResponse);
// RecvPacket defines a rpc handler method for MsgRecvPacket.
rpc RecvPacket(MsgRecvPacket) returns (MsgRecvPacketResponse);
// Timeout defines a rpc handler method for MsgTimeout.
rpc Timeout(MsgTimeout) returns (MsgTimeoutResponse);
// TimeoutOnClose defines a rpc handler method for MsgTimeoutOnClose.
rpc TimeoutOnClose(MsgTimeoutOnClose) returns (MsgTimeoutOnCloseResponse);
// Acknowledgement defines a rpc handler method for MsgAcknowledgement.
rpc Acknowledgement(MsgAcknowledgement) returns (MsgAcknowledgementResponse);
}
// MsgChannelOpenInit defines an sdk.Msg to initialize a channel handshake. It
// is called by a relayer on Chain A.
message MsgChannelOpenInit {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
Channel channel = 2 [(gogoproto.nullable) = false];
string signer = 3;
}
// MsgChannelOpenInitResponse defines the Msg/ChannelOpenInit response type.
message MsgChannelOpenInitResponse {}
// MsgChannelOpenInit defines a msg sent by a Relayer to try to open a channel
// on Chain B.
message MsgChannelOpenTry {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
// in the case of crossing hello's, when both chains call OpenInit, we need the channel identifier
// of the previous channel in state INIT
string previous_channel_id = 2 [(gogoproto.moretags) = "yaml:\"previous_channel_id\""];
Channel channel = 3 [(gogoproto.nullable) = false];
string counterparty_version = 4 [(gogoproto.moretags) = "yaml:\"counterparty_version\""];
bytes proof_init = 5 [(gogoproto.moretags) = "yaml:\"proof_init\""];
ibc.core.client.v1.Height proof_height = 6
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 7;
}
// MsgChannelOpenTryResponse defines the Msg/ChannelOpenTry response type.
message MsgChannelOpenTryResponse {}
// MsgChannelOpenAck defines a msg sent by a Relayer to Chain A to acknowledge
// the change of channel state to TRYOPEN on Chain B.
message MsgChannelOpenAck {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
string counterparty_channel_id = 3 [(gogoproto.moretags) = "yaml:\"counterparty_channel_id\""];
string counterparty_version = 4 [(gogoproto.moretags) = "yaml:\"counterparty_version\""];
bytes proof_try = 5 [(gogoproto.moretags) = "yaml:\"proof_try\""];
ibc.core.client.v1.Height proof_height = 6
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 7;
}
// MsgChannelOpenAckResponse defines the Msg/ChannelOpenAck response type.
message MsgChannelOpenAckResponse {}
// MsgChannelOpenConfirm defines a msg sent by a Relayer to Chain B to
// acknowledge the change of channel state to OPEN on Chain A.
message MsgChannelOpenConfirm {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
bytes proof_ack = 3 [(gogoproto.moretags) = "yaml:\"proof_ack\""];
ibc.core.client.v1.Height proof_height = 4
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 5;
}
// MsgChannelOpenConfirmResponse defines the Msg/ChannelOpenConfirm response type.
message MsgChannelOpenConfirmResponse {}
// MsgChannelCloseInit defines a msg sent by a Relayer to Chain A
// to close a channel with Chain B.
message MsgChannelCloseInit {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
string signer = 3;
}
// MsgChannelCloseInitResponse defines the Msg/ChannelCloseInit response type.
message MsgChannelCloseInitResponse {}
// MsgChannelCloseConfirm defines a msg sent by a Relayer to Chain B
// to acknowledge the change of channel state to CLOSED on Chain A.
message MsgChannelCloseConfirm {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string port_id = 1 [(gogoproto.moretags) = "yaml:\"port_id\""];
string channel_id = 2 [(gogoproto.moretags) = "yaml:\"channel_id\""];
bytes proof_init = 3 [(gogoproto.moretags) = "yaml:\"proof_init\""];
ibc.core.client.v1.Height proof_height = 4
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 5;
}
// MsgChannelCloseConfirmResponse defines the Msg/ChannelCloseConfirm response type.
message MsgChannelCloseConfirmResponse {}
// MsgRecvPacket receives incoming IBC packet
message MsgRecvPacket {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
Packet packet = 1 [(gogoproto.nullable) = false];
bytes proof_commitment = 2 [(gogoproto.moretags) = "yaml:\"proof_commitment\""];
ibc.core.client.v1.Height proof_height = 3
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 4;
}
// MsgRecvPacketResponse defines the Msg/RecvPacket response type.
message MsgRecvPacketResponse {}
// MsgTimeout receives timed-out packet
message MsgTimeout {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
Packet packet = 1 [(gogoproto.nullable) = false];
bytes proof_unreceived = 2 [(gogoproto.moretags) = "yaml:\"proof_unreceived\""];
ibc.core.client.v1.Height proof_height = 3
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
uint64 next_sequence_recv = 4 [(gogoproto.moretags) = "yaml:\"next_sequence_recv\""];
string signer = 5;
}
// MsgTimeoutResponse defines the Msg/Timeout response type.
message MsgTimeoutResponse {}
// MsgTimeoutOnClose timed-out packet upon counterparty channel closure.
message MsgTimeoutOnClose {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
Packet packet = 1 [(gogoproto.nullable) = false];
bytes proof_unreceived = 2 [(gogoproto.moretags) = "yaml:\"proof_unreceived\""];
bytes proof_close = 3 [(gogoproto.moretags) = "yaml:\"proof_close\""];
ibc.core.client.v1.Height proof_height = 4
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
uint64 next_sequence_recv = 5 [(gogoproto.moretags) = "yaml:\"next_sequence_recv\""];
string signer = 6;
}
// MsgTimeoutOnCloseResponse defines the Msg/TimeoutOnClose response type.
message MsgTimeoutOnCloseResponse {}
// MsgAcknowledgement receives incoming IBC acknowledgement
message MsgAcknowledgement {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
Packet packet = 1 [(gogoproto.nullable) = false];
bytes acknowledgement = 2;
bytes proof_acked = 3 [(gogoproto.moretags) = "yaml:\"proof_acked\""];
ibc.core.client.v1.Height proof_height = 4
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 5;
}
// MsgAcknowledgementResponse defines the Msg/Acknowledgement response type.
message MsgAcknowledgementResponse {}

View File

@ -1,74 +0,0 @@
syntax = "proto3";
package ibc.core.client.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
// IdentifiedClientState defines a client state with an additional client
// identifier field.
message IdentifiedClientState {
// client identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// client state
google.protobuf.Any client_state = 2 [(gogoproto.moretags) = "yaml:\"client_state\""];
}
// ConsensusStateWithHeight defines a consensus state with an additional height field.
message ConsensusStateWithHeight {
// consensus state height
Height height = 1 [(gogoproto.nullable) = false];
// consensus state
google.protobuf.Any consensus_state = 2 [(gogoproto.moretags) = "yaml\"consensus_state\""];
}
// ClientConsensusStates defines all the stored consensus states for a given
// client.
message ClientConsensusStates {
// client identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// consensus states and their heights associated with the client
repeated ConsensusStateWithHeight consensus_states = 2
[(gogoproto.moretags) = "yaml:\"consensus_states\"", (gogoproto.nullable) = false];
}
// ClientUpdateProposal is a governance proposal. If it passes, the client is
// updated with the provided header. The update may fail if the header is not
// valid given certain conditions specified by the client implementation.
message ClientUpdateProposal {
option (gogoproto.goproto_getters) = false;
// the title of the update proposal
string title = 1;
// the description of the proposal
string description = 2;
// the client identifier for the client to be updated if the proposal passes
string client_id = 3 [(gogoproto.moretags) = "yaml:\"client_id\""];
// the header used to update the client if the proposal passes
google.protobuf.Any header = 4;
}
// Height is a monotonically increasing data type
// that can be compared against another Height for the purposes of updating and
// freezing clients
//
// Normally the RevisionHeight is incremented at each height while keeping RevisionNumber
// the same. However some consensus algorithms may choose to reset the
// height in certain conditions e.g. hard forks, state-machine breaking changes
// In these cases, the RevisionNumber is incremented so that height continues to
// be monitonically increasing even as the RevisionHeight gets reset
message Height {
option (gogoproto.goproto_getters) = false;
option (gogoproto.goproto_stringer) = false;
// the revision that the client is currently on
uint64 revision_number = 1 [(gogoproto.moretags) = "yaml:\"revision_number\""];
// the height within the given revision
uint64 revision_height = 2 [(gogoproto.moretags) = "yaml:\"revision_height\""];
}
// Params defines the set of IBC light client parameters.
message Params {
// allowed_clients defines the list of allowed client state types.
repeated string allowed_clients = 1 [(gogoproto.moretags) = "yaml:\"allowed_clients\""];
}

View File

@ -1,46 +0,0 @@
syntax = "proto3";
package ibc.core.client.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types";
import "ibc/core/client/v1/client.proto";
import "gogoproto/gogo.proto";
// GenesisState defines the ibc client submodule's genesis state.
message GenesisState {
// client states with their corresponding identifiers
repeated IdentifiedClientState clients = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "IdentifiedClientStates"];
// consensus states from each client
repeated ClientConsensusStates clients_consensus = 2 [
(gogoproto.nullable) = false,
(gogoproto.castrepeated) = "ClientsConsensusStates",
(gogoproto.moretags) = "yaml:\"clients_consensus\""
];
// metadata from each client
repeated IdentifiedGenesisMetadata clients_metadata = 3
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"clients_metadata\""];
Params params = 4 [(gogoproto.nullable) = false];
// create localhost on initialization
bool create_localhost = 5 [(gogoproto.moretags) = "yaml:\"create_localhost\""];
// the sequence for the next generated client identifier
uint64 next_client_sequence = 6 [(gogoproto.moretags) = "yaml:\"next_client_sequence\""];
}
// GenesisMetadata defines the genesis type for metadata that clients may return
// with ExportMetadata
message GenesisMetadata {
option (gogoproto.goproto_getters) = false;
// store key of metadata without clientID-prefix
bytes key = 1;
// metadata value
bytes value = 2;
}
// IdentifiedGenesisMetadata has the client metadata with the corresponding client id.
message IdentifiedGenesisMetadata {
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
repeated GenesisMetadata client_metadata = 2
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"client_metadata\""];
}

View File

@ -1,130 +0,0 @@
syntax = "proto3";
package ibc.core.client.v1;
import "cosmos/base/query/v1beta1/pagination.proto";
import "ibc/core/client/v1/client.proto";
import "google/protobuf/any.proto";
import "google/api/annotations.proto";
import "gogoproto/gogo.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types";
// Query provides defines the gRPC querier service
service Query {
// ClientState queries an IBC light client.
rpc ClientState(QueryClientStateRequest) returns (QueryClientStateResponse) {
option (google.api.http).get = "/ibc/core/client/v1beta1/client_states/{client_id}";
}
// ClientStates queries all the IBC light clients of a chain.
rpc ClientStates(QueryClientStatesRequest) returns (QueryClientStatesResponse) {
option (google.api.http).get = "/ibc/core/client/v1beta1/client_states";
}
// ConsensusState queries a consensus state associated with a client state at
// a given height.
rpc ConsensusState(QueryConsensusStateRequest) returns (QueryConsensusStateResponse) {
option (google.api.http).get = "/ibc/core/client/v1beta1/consensus_states/{client_id}/revision/{revision_number}/"
"height/{revision_height}";
}
// ConsensusStates queries all the consensus state associated with a given
// client.
rpc ConsensusStates(QueryConsensusStatesRequest) returns (QueryConsensusStatesResponse) {
option (google.api.http).get = "/ibc/core/client/v1beta1/consensus_states/{client_id}";
}
// ClientParams queries all parameters of the ibc client.
rpc ClientParams(QueryClientParamsRequest) returns (QueryClientParamsResponse) {
option (google.api.http).get = "/ibc/client/v1beta1/params";
}
}
// QueryClientStateRequest is the request type for the Query/ClientState RPC
// method
message QueryClientStateRequest {
// client state unique identifier
string client_id = 1;
}
// QueryClientStateResponse is the response type for the Query/ClientState RPC
// method. Besides the client state, it includes a proof and the height from
// which the proof was retrieved.
message QueryClientStateResponse {
// client state associated with the request identifier
google.protobuf.Any client_state = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryClientStatesRequest is the request type for the Query/ClientStates RPC
// method
message QueryClientStatesRequest {
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryClientStatesResponse is the response type for the Query/ClientStates RPC
// method.
message QueryClientStatesResponse {
// list of stored ClientStates of the chain.
repeated IdentifiedClientState client_states = 1
[(gogoproto.nullable) = false, (gogoproto.castrepeated) = "IdentifiedClientStates"];
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
// QueryConsensusStateRequest is the request type for the Query/ConsensusState
// RPC method. Besides the consensus state, it includes a proof and the height
// from which the proof was retrieved.
message QueryConsensusStateRequest {
// client identifier
string client_id = 1;
// consensus state revision number
uint64 revision_number = 2;
// consensus state revision height
uint64 revision_height = 3;
// latest_height overrrides the height field and queries the latest stored
// ConsensusState
bool latest_height = 4;
}
// QueryConsensusStateResponse is the response type for the Query/ConsensusState
// RPC method
message QueryConsensusStateResponse {
// consensus state associated with the client identifier at the given height
google.protobuf.Any consensus_state = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryConsensusStatesRequest is the request type for the Query/ConsensusStates
// RPC method.
message QueryConsensusStatesRequest {
// client identifier
string client_id = 1;
// pagination request
cosmos.base.query.v1beta1.PageRequest pagination = 2;
}
// QueryConsensusStatesResponse is the response type for the
// Query/ConsensusStates RPC method
message QueryConsensusStatesResponse {
// consensus states associated with the identifier
repeated ConsensusStateWithHeight consensus_states = 1 [(gogoproto.nullable) = false];
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
}
// QueryClientParamsRequest is the request type for the Query/ClientParams RPC method.
message QueryClientParamsRequest {}
// QueryClientParamsResponse is the response type for the Query/ClientParams RPC method.
message QueryClientParamsResponse {
// params defines the parameters of the module.
Params params = 1;
}

View File

@ -1,96 +0,0 @@
syntax = "proto3";
package ibc.core.client.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "ibc/core/client/v1/client.proto";
// Msg defines the ibc/client Msg service.
service Msg {
// CreateClient defines a rpc handler method for MsgCreateClient.
rpc CreateClient(MsgCreateClient) returns (MsgCreateClientResponse);
// UpdateClient defines a rpc handler method for MsgUpdateClient.
rpc UpdateClient(MsgUpdateClient) returns (MsgUpdateClientResponse);
// UpgradeClient defines a rpc handler method for MsgUpgradeClient.
rpc UpgradeClient(MsgUpgradeClient) returns (MsgUpgradeClientResponse);
// SubmitMisbehaviour defines a rpc handler method for MsgSubmitMisbehaviour.
rpc SubmitMisbehaviour(MsgSubmitMisbehaviour) returns (MsgSubmitMisbehaviourResponse);
}
// MsgCreateClient defines a message to create an IBC client
message MsgCreateClient {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// light client state
google.protobuf.Any client_state = 1 [(gogoproto.moretags) = "yaml:\"client_state\""];
// consensus state associated with the client that corresponds to a given
// height.
google.protobuf.Any consensus_state = 2 [(gogoproto.moretags) = "yaml:\"consensus_state\""];
// signer address
string signer = 3;
}
// MsgCreateClientResponse defines the Msg/CreateClient response type.
message MsgCreateClientResponse {}
// MsgUpdateClient defines an sdk.Msg to update a IBC client state using
// the given header.
message MsgUpdateClient {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// client unique identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// header to update the light client
google.protobuf.Any header = 2;
// signer address
string signer = 3;
}
// MsgUpdateClientResponse defines the Msg/UpdateClient response type.
message MsgUpdateClientResponse {}
// MsgUpgradeClient defines an sdk.Msg to upgrade an IBC client to a new client state
message MsgUpgradeClient {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// client unique identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// upgraded client state
google.protobuf.Any client_state = 2 [(gogoproto.moretags) = "yaml:\"client_state\""];
// upgraded consensus state, only contains enough information to serve as a basis of trust in update logic
google.protobuf.Any consensus_state = 3 [(gogoproto.moretags) = "yaml:\"consensus_state\""];
// proof that old chain committed to new client
bytes proof_upgrade_client = 4 [(gogoproto.moretags) = "yaml:\"proof_upgrade_client\""];
// proof that old chain committed to new consensus state
bytes proof_upgrade_consensus_state = 5 [(gogoproto.moretags) = "yaml:\"proof_upgrade_consensus_state\""];
// signer address
string signer = 6;
}
// MsgUpgradeClientResponse defines the Msg/UpgradeClient response type.
message MsgUpgradeClientResponse {}
// MsgSubmitMisbehaviour defines an sdk.Msg type that submits Evidence for
// light client misbehaviour.
message MsgSubmitMisbehaviour {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
// client unique identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// misbehaviour used for freezing the light client
google.protobuf.Any misbehaviour = 2;
// signer address
string signer = 3;
}
// MsgSubmitMisbehaviourResponse defines the Msg/SubmitMisbehaviour response type.
message MsgSubmitMisbehaviourResponse {}

View File

@ -1,40 +0,0 @@
syntax = "proto3";
package ibc.core.commitment.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types";
import "gogoproto/gogo.proto";
import "confio/proofs.proto";
// MerkleRoot defines a merkle root hash.
// In the Cosmos SDK, the AppHash of a block header becomes the root.
message MerkleRoot {
option (gogoproto.goproto_getters) = false;
bytes hash = 1;
}
// MerklePrefix is merkle path prefixed to the key.
// The constructed key from the Path and the key will be append(Path.KeyPath,
// append(Path.KeyPrefix, key...))
message MerklePrefix {
bytes key_prefix = 1 [(gogoproto.moretags) = "yaml:\"key_prefix\""];
}
// MerklePath is the path used to verify commitment proofs, which can be an
// arbitrary structured object (defined by a commitment type).
// MerklePath is represented from root-to-leaf
message MerklePath {
option (gogoproto.goproto_stringer) = false;
repeated string key_path = 1 [(gogoproto.moretags) = "yaml:\"key_path\""];
}
// MerkleProof is a wrapper type over a chain of CommitmentProofs.
// It demonstrates membership or non-membership for an element or set of
// elements, verifiable in conjunction with a known commitment root. Proofs
// should be succinct.
// MerkleProofs are ordered from leaf-to-root
message MerkleProof {
repeated ics23.CommitmentProof proofs = 1;
}

View File

@ -1,104 +0,0 @@
syntax = "proto3";
package ibc.core.connection.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types";
import "gogoproto/gogo.proto";
import "ibc/core/commitment/v1/commitment.proto";
// ICS03 - Connection Data Structures as defined in
// https://github.com/cosmos/ics/tree/master/spec/ics-003-connection-semantics#data-structures
// ConnectionEnd defines a stateful object on a chain connected to another
// separate one.
// NOTE: there must only be 2 defined ConnectionEnds to establish
// a connection between two chains.
message ConnectionEnd {
option (gogoproto.goproto_getters) = false;
// client associated with this connection.
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// IBC version which can be utilised to determine encodings or protocols for
// channels or packets utilising this connection.
repeated Version versions = 2;
// current state of the connection end.
State state = 3;
// counterparty chain associated with this connection.
Counterparty counterparty = 4 [(gogoproto.nullable) = false];
// delay period that must pass before a consensus state can be used for packet-verification
// NOTE: delay period logic is only implemented by some clients.
uint64 delay_period = 5 [(gogoproto.moretags) = "yaml:\"delay_period\""];
}
// IdentifiedConnection defines a connection with additional connection
// identifier field.
message IdentifiedConnection {
option (gogoproto.goproto_getters) = false;
// connection identifier.
string id = 1 [(gogoproto.moretags) = "yaml:\"id\""];
// client associated with this connection.
string client_id = 2 [(gogoproto.moretags) = "yaml:\"client_id\""];
// IBC version which can be utilised to determine encodings or protocols for
// channels or packets utilising this connection
repeated Version versions = 3;
// current state of the connection end.
State state = 4;
// counterparty chain associated with this connection.
Counterparty counterparty = 5 [(gogoproto.nullable) = false];
// delay period associated with this connection.
uint64 delay_period = 6 [(gogoproto.moretags) = "yaml:\"delay_period\""];
}
// State defines if a connection is in one of the following states:
// INIT, TRYOPEN, OPEN or UNINITIALIZED.
enum State {
option (gogoproto.goproto_enum_prefix) = false;
// Default State
STATE_UNINITIALIZED_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "UNINITIALIZED"];
// A connection end has just started the opening handshake.
STATE_INIT = 1 [(gogoproto.enumvalue_customname) = "INIT"];
// A connection end has acknowledged the handshake step on the counterparty
// chain.
STATE_TRYOPEN = 2 [(gogoproto.enumvalue_customname) = "TRYOPEN"];
// A connection end has completed the handshake.
STATE_OPEN = 3 [(gogoproto.enumvalue_customname) = "OPEN"];
}
// Counterparty defines the counterparty chain associated with a connection end.
message Counterparty {
option (gogoproto.goproto_getters) = false;
// identifies the client on the counterparty chain associated with a given
// connection.
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// identifies the connection end on the counterparty chain associated with a
// given connection.
string connection_id = 2 [(gogoproto.moretags) = "yaml:\"connection_id\""];
// commitment merkle prefix of the counterparty chain.
ibc.core.commitment.v1.MerklePrefix prefix = 3 [(gogoproto.nullable) = false];
}
// ClientPaths define all the connection paths for a client state.
message ClientPaths {
// list of connection paths
repeated string paths = 1;
}
// ConnectionPaths define all the connection paths for a given client state.
message ConnectionPaths {
// client state unique identifier
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// list of connection paths
repeated string paths = 2;
}
// Version defines the versioning scheme used to negotiate the IBC verison in
// the connection handshake.
message Version {
option (gogoproto.goproto_getters) = false;
// unique version identifier
string identifier = 1;
// list of features compatible with the specified identifier
repeated string features = 2;
}

View File

@ -1,16 +0,0 @@
syntax = "proto3";
package ibc.core.connection.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types";
import "gogoproto/gogo.proto";
import "ibc/core/connection/v1/connection.proto";
// GenesisState defines the ibc connection submodule's genesis state.
message GenesisState {
repeated IdentifiedConnection connections = 1 [(gogoproto.nullable) = false];
repeated ConnectionPaths client_connection_paths = 2
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"client_connection_paths\""];
// the sequence for the next generated connection identifier
uint64 next_connection_sequence = 3 [(gogoproto.moretags) = "yaml:\"next_connection_sequence\""];
}

View File

@ -1,137 +0,0 @@
syntax = "proto3";
package ibc.core.connection.v1;
import "gogoproto/gogo.proto";
import "cosmos/base/query/v1beta1/pagination.proto";
import "ibc/core/client/v1/client.proto";
import "ibc/core/connection/v1/connection.proto";
import "google/api/annotations.proto";
import "google/protobuf/any.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types";
// Query provides defines the gRPC querier service
service Query {
// Connection queries an IBC connection end.
rpc Connection(QueryConnectionRequest) returns (QueryConnectionResponse) {
option (google.api.http).get = "/ibc/core/connection/v1beta1/connections/{connection_id}";
}
// Connections queries all the IBC connections of a chain.
rpc Connections(QueryConnectionsRequest) returns (QueryConnectionsResponse) {
option (google.api.http).get = "/ibc/core/connection/v1beta1/connections";
}
// ClientConnections queries the connection paths associated with a client
// state.
rpc ClientConnections(QueryClientConnectionsRequest) returns (QueryClientConnectionsResponse) {
option (google.api.http).get = "/ibc/core/connection/v1beta1/client_connections/{client_id}";
}
// ConnectionClientState queries the client state associated with the
// connection.
rpc ConnectionClientState(QueryConnectionClientStateRequest) returns (QueryConnectionClientStateResponse) {
option (google.api.http).get = "/ibc/core/connection/v1beta1/connections/{connection_id}/client_state";
}
// ConnectionConsensusState queries the consensus state associated with the
// connection.
rpc ConnectionConsensusState(QueryConnectionConsensusStateRequest) returns (QueryConnectionConsensusStateResponse) {
option (google.api.http).get = "/ibc/core/connection/v1beta1/connections/{connection_id}/consensus_state/"
"revision/{revision_number}/height/{revision_height}";
}
}
// QueryConnectionRequest is the request type for the Query/Connection RPC
// method
message QueryConnectionRequest {
// connection unique identifier
string connection_id = 1;
}
// QueryConnectionResponse is the response type for the Query/Connection RPC
// method. Besides the connection end, it includes a proof and the height from
// which the proof was retrieved.
message QueryConnectionResponse {
// connection associated with the request identifier
ibc.core.connection.v1.ConnectionEnd connection = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryConnectionsRequest is the request type for the Query/Connections RPC
// method
message QueryConnectionsRequest {
cosmos.base.query.v1beta1.PageRequest pagination = 1;
}
// QueryConnectionsResponse is the response type for the Query/Connections RPC
// method.
message QueryConnectionsResponse {
// list of stored connections of the chain.
repeated ibc.core.connection.v1.IdentifiedConnection connections = 1;
// pagination response
cosmos.base.query.v1beta1.PageResponse pagination = 2;
// query block height
ibc.core.client.v1.Height height = 3 [(gogoproto.nullable) = false];
}
// QueryClientConnectionsRequest is the request type for the
// Query/ClientConnections RPC method
message QueryClientConnectionsRequest {
// client identifier associated with a connection
string client_id = 1;
}
// QueryClientConnectionsResponse is the response type for the
// Query/ClientConnections RPC method
message QueryClientConnectionsResponse {
// slice of all the connection paths associated with a client.
repeated string connection_paths = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was generated
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryConnectionClientStateRequest is the request type for the
// Query/ConnectionClientState RPC method
message QueryConnectionClientStateRequest {
// connection identifier
string connection_id = 1 [(gogoproto.moretags) = "yaml:\"connection_id\""];
}
// QueryConnectionClientStateResponse is the response type for the
// Query/ConnectionClientState RPC method
message QueryConnectionClientStateResponse {
// client state associated with the channel
ibc.core.client.v1.IdentifiedClientState identified_client_state = 1;
// merkle proof of existence
bytes proof = 2;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 3 [(gogoproto.nullable) = false];
}
// QueryConnectionConsensusStateRequest is the request type for the
// Query/ConnectionConsensusState RPC method
message QueryConnectionConsensusStateRequest {
// connection identifier
string connection_id = 1 [(gogoproto.moretags) = "yaml:\"connection_id\""];
uint64 revision_number = 2;
uint64 revision_height = 3;
}
// QueryConnectionConsensusStateResponse is the response type for the
// Query/ConnectionConsensusState RPC method
message QueryConnectionConsensusStateResponse {
// consensus state associated with the channel
google.protobuf.Any consensus_state = 1;
// client ID associated with the consensus state
string client_id = 2;
// merkle proof of existence
bytes proof = 3;
// height at which the proof was retrieved
ibc.core.client.v1.Height proof_height = 4 [(gogoproto.nullable) = false];
}

View File

@ -1,115 +0,0 @@
syntax = "proto3";
package ibc.core.connection.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
import "ibc/core/client/v1/client.proto";
import "ibc/core/connection/v1/connection.proto";
// Msg defines the ibc/connection Msg service.
service Msg {
// ConnectionOpenInit defines a rpc handler method for MsgConnectionOpenInit.
rpc ConnectionOpenInit(MsgConnectionOpenInit) returns (MsgConnectionOpenInitResponse);
// ConnectionOpenTry defines a rpc handler method for MsgConnectionOpenTry.
rpc ConnectionOpenTry(MsgConnectionOpenTry) returns (MsgConnectionOpenTryResponse);
// ConnectionOpenAck defines a rpc handler method for MsgConnectionOpenAck.
rpc ConnectionOpenAck(MsgConnectionOpenAck) returns (MsgConnectionOpenAckResponse);
// ConnectionOpenConfirm defines a rpc handler method for MsgConnectionOpenConfirm.
rpc ConnectionOpenConfirm(MsgConnectionOpenConfirm) returns (MsgConnectionOpenConfirmResponse);
}
// MsgConnectionOpenInit defines the msg sent by an account on Chain A to
// initialize a connection with Chain B.
message MsgConnectionOpenInit {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
Counterparty counterparty = 2 [(gogoproto.nullable) = false];
Version version = 3;
uint64 delay_period = 4 [(gogoproto.moretags) = "yaml:\"delay_period\""];
string signer = 5;
}
// MsgConnectionOpenInitResponse defines the Msg/ConnectionOpenInit response type.
message MsgConnectionOpenInitResponse {}
// MsgConnectionOpenTry defines a msg sent by a Relayer to try to open a
// connection on Chain B.
message MsgConnectionOpenTry {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
// in the case of crossing hello's, when both chains call OpenInit, we need the connection identifier
// of the previous connection in state INIT
string previous_connection_id = 2 [(gogoproto.moretags) = "yaml:\"previous_connection_id\""];
google.protobuf.Any client_state = 3 [(gogoproto.moretags) = "yaml:\"client_state\""];
Counterparty counterparty = 4 [(gogoproto.nullable) = false];
uint64 delay_period = 5 [(gogoproto.moretags) = "yaml:\"delay_period\""];
repeated Version counterparty_versions = 6 [(gogoproto.moretags) = "yaml:\"counterparty_versions\""];
ibc.core.client.v1.Height proof_height = 7
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
// proof of the initialization the connection on Chain A: `UNITIALIZED ->
// INIT`
bytes proof_init = 8 [(gogoproto.moretags) = "yaml:\"proof_init\""];
// proof of client state included in message
bytes proof_client = 9 [(gogoproto.moretags) = "yaml:\"proof_client\""];
// proof of client consensus state
bytes proof_consensus = 10 [(gogoproto.moretags) = "yaml:\"proof_consensus\""];
ibc.core.client.v1.Height consensus_height = 11
[(gogoproto.moretags) = "yaml:\"consensus_height\"", (gogoproto.nullable) = false];
string signer = 12;
}
// MsgConnectionOpenTryResponse defines the Msg/ConnectionOpenTry response type.
message MsgConnectionOpenTryResponse {}
// MsgConnectionOpenAck defines a msg sent by a Relayer to Chain A to
// acknowledge the change of connection state to TRYOPEN on Chain B.
message MsgConnectionOpenAck {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string connection_id = 1 [(gogoproto.moretags) = "yaml:\"connection_id\""];
string counterparty_connection_id = 2 [(gogoproto.moretags) = "yaml:\"counterparty_connection_id\""];
Version version = 3;
google.protobuf.Any client_state = 4 [(gogoproto.moretags) = "yaml:\"client_state\""];
ibc.core.client.v1.Height proof_height = 5
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
// proof of the initialization the connection on Chain B: `UNITIALIZED ->
// TRYOPEN`
bytes proof_try = 6 [(gogoproto.moretags) = "yaml:\"proof_try\""];
// proof of client state included in message
bytes proof_client = 7 [(gogoproto.moretags) = "yaml:\"proof_client\""];
// proof of client consensus state
bytes proof_consensus = 8 [(gogoproto.moretags) = "yaml:\"proof_consensus\""];
ibc.core.client.v1.Height consensus_height = 9
[(gogoproto.moretags) = "yaml:\"consensus_height\"", (gogoproto.nullable) = false];
string signer = 10;
}
// MsgConnectionOpenAckResponse defines the Msg/ConnectionOpenAck response type.
message MsgConnectionOpenAckResponse {}
// MsgConnectionOpenConfirm defines a msg sent by a Relayer to Chain B to
// acknowledge the change of connection state to OPEN on Chain A.
message MsgConnectionOpenConfirm {
option (gogoproto.equal) = false;
option (gogoproto.goproto_getters) = false;
string connection_id = 1 [(gogoproto.moretags) = "yaml:\"connection_id\""];
// proof for the change of the connection state on Chain A: `INIT -> OPEN`
bytes proof_ack = 2 [(gogoproto.moretags) = "yaml:\"proof_ack\""];
ibc.core.client.v1.Height proof_height = 3
[(gogoproto.moretags) = "yaml:\"proof_height\"", (gogoproto.nullable) = false];
string signer = 4;
}
// MsgConnectionOpenConfirmResponse defines the Msg/ConnectionOpenConfirm response type.
message MsgConnectionOpenConfirmResponse {}

View File

@ -1,22 +0,0 @@
syntax = "proto3";
package ibc.core.types.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/core/types";
import "gogoproto/gogo.proto";
import "ibc/core/client/v1/genesis.proto";
import "ibc/core/connection/v1/genesis.proto";
import "ibc/core/channel/v1/genesis.proto";
// GenesisState defines the ibc module's genesis state.
message GenesisState {
// ICS002 - Clients genesis state
ibc.core.client.v1.GenesisState client_genesis = 1
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"client_genesis\""];
// ICS003 - Connections genesis state
ibc.core.connection.v1.GenesisState connection_genesis = 2
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"connection_genesis\""];
// ICS004 - Channel genesis state
ibc.core.channel.v1.GenesisState channel_genesis = 3
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"channel_genesis\""];
}

View File

@ -1,17 +0,0 @@
syntax = "proto3";
package ibc.lightclients.localhost.v1;
import "gogoproto/gogo.proto";
import "ibc/core/client/v1/client.proto";
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/09-localhost/types";
// ClientState defines a loopback (localhost) client. It requires (read-only)
// access to keys outside the client prefix.
message ClientState {
option (gogoproto.goproto_getters) = false;
// self chain ID
string chain_id = 1 [(gogoproto.moretags) = "yaml:\"chain_id\""];
// self latest block height
ibc.core.client.v1.Height height = 2 [(gogoproto.nullable) = false];
}

View File

@ -1,186 +0,0 @@
syntax = "proto3";
package ibc.lightclients.solomachine.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/06-solomachine/types";
import "ibc/core/connection/v1/connection.proto";
import "ibc/core/channel/v1/channel.proto";
import "gogoproto/gogo.proto";
import "google/protobuf/any.proto";
// ClientState defines a solo machine client that tracks the current consensus
// state and if the client is frozen.
message ClientState {
option (gogoproto.goproto_getters) = false;
// latest sequence of the client state
uint64 sequence = 1;
// frozen sequence of the solo machine
uint64 frozen_sequence = 2 [(gogoproto.moretags) = "yaml:\"frozen_sequence\""];
ConsensusState consensus_state = 3 [(gogoproto.moretags) = "yaml:\"consensus_state\""];
// when set to true, will allow governance to update a solo machine client.
// The client will be unfrozen if it is frozen.
bool allow_update_after_proposal = 4 [(gogoproto.moretags) = "yaml:\"allow_update_after_proposal\""];
}
// ConsensusState defines a solo machine consensus state. The sequence of a consensus state
// is contained in the "height" key used in storing the consensus state.
message ConsensusState {
option (gogoproto.goproto_getters) = false;
// public key of the solo machine
google.protobuf.Any public_key = 1 [(gogoproto.moretags) = "yaml:\"public_key\""];
// diversifier allows the same public key to be re-used across different solo machine clients
// (potentially on different chains) without being considered misbehaviour.
string diversifier = 2;
uint64 timestamp = 3;
}
// Header defines a solo machine consensus header
message Header {
option (gogoproto.goproto_getters) = false;
// sequence to update solo machine public key at
uint64 sequence = 1;
uint64 timestamp = 2;
bytes signature = 3;
google.protobuf.Any new_public_key = 4 [(gogoproto.moretags) = "yaml:\"new_public_key\""];
string new_diversifier = 5 [(gogoproto.moretags) = "yaml:\"new_diversifier\""];
}
// Misbehaviour defines misbehaviour for a solo machine which consists
// of a sequence and two signatures over different messages at that sequence.
message Misbehaviour {
option (gogoproto.goproto_getters) = false;
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
uint64 sequence = 2;
SignatureAndData signature_one = 3 [(gogoproto.moretags) = "yaml:\"signature_one\""];
SignatureAndData signature_two = 4 [(gogoproto.moretags) = "yaml:\"signature_two\""];
}
// SignatureAndData contains a signature and the data signed over to create that
// signature.
message SignatureAndData {
option (gogoproto.goproto_getters) = false;
bytes signature = 1;
DataType data_type = 2 [(gogoproto.moretags) = "yaml:\"data_type\""];
bytes data = 3;
uint64 timestamp = 4;
}
// TimestampedSignatureData contains the signature data and the timestamp of the
// signature.
message TimestampedSignatureData {
option (gogoproto.goproto_getters) = false;
bytes signature_data = 1 [(gogoproto.moretags) = "yaml:\"signature_data\""];
uint64 timestamp = 2;
}
// SignBytes defines the signed bytes used for signature verification.
message SignBytes {
option (gogoproto.goproto_getters) = false;
uint64 sequence = 1;
uint64 timestamp = 2;
string diversifier = 3;
// type of the data used
DataType data_type = 4 [(gogoproto.moretags) = "yaml:\"data_type\""];
// marshaled data
bytes data = 5;
}
// DataType defines the type of solo machine proof being created. This is done to preserve uniqueness of different
// data sign byte encodings.
enum DataType {
option (gogoproto.goproto_enum_prefix) = false;
// Default State
DATA_TYPE_UNINITIALIZED_UNSPECIFIED = 0 [(gogoproto.enumvalue_customname) = "UNSPECIFIED"];
// Data type for client state verification
DATA_TYPE_CLIENT_STATE = 1 [(gogoproto.enumvalue_customname) = "CLIENT"];
// Data type for consensus state verification
DATA_TYPE_CONSENSUS_STATE = 2 [(gogoproto.enumvalue_customname) = "CONSENSUS"];
// Data type for connection state verification
DATA_TYPE_CONNECTION_STATE = 3 [(gogoproto.enumvalue_customname) = "CONNECTION"];
// Data type for channel state verification
DATA_TYPE_CHANNEL_STATE = 4 [(gogoproto.enumvalue_customname) = "CHANNEL"];
// Data type for packet commitment verification
DATA_TYPE_PACKET_COMMITMENT = 5 [(gogoproto.enumvalue_customname) = "PACKETCOMMITMENT"];
// Data type for packet acknowledgement verification
DATA_TYPE_PACKET_ACKNOWLEDGEMENT = 6 [(gogoproto.enumvalue_customname) = "PACKETACKNOWLEDGEMENT"];
// Data type for packet receipt absence verification
DATA_TYPE_PACKET_RECEIPT_ABSENCE = 7 [(gogoproto.enumvalue_customname) = "PACKETRECEIPTABSENCE"];
// Data type for next sequence recv verification
DATA_TYPE_NEXT_SEQUENCE_RECV = 8 [(gogoproto.enumvalue_customname) = "NEXTSEQUENCERECV"];
// Data type for header verification
DATA_TYPE_HEADER = 9 [(gogoproto.enumvalue_customname) = "HEADER"];
}
// HeaderData returns the SignBytes data for update verification.
message HeaderData {
option (gogoproto.goproto_getters) = false;
// header public key
google.protobuf.Any new_pub_key = 1 [(gogoproto.moretags) = "yaml:\"new_pub_key\""];
// header diversifier
string new_diversifier = 2 [(gogoproto.moretags) = "yaml:\"new_diversifier\""];
}
// ClientStateData returns the SignBytes data for client state verification.
message ClientStateData {
option (gogoproto.goproto_getters) = false;
bytes path = 1;
google.protobuf.Any client_state = 2 [(gogoproto.moretags) = "yaml:\"client_state\""];
}
// ConsensusStateData returns the SignBytes data for consensus state
// verification.
message ConsensusStateData {
option (gogoproto.goproto_getters) = false;
bytes path = 1;
google.protobuf.Any consensus_state = 2 [(gogoproto.moretags) = "yaml:\"consensus_state\""];
}
// ConnectionStateData returns the SignBytes data for connection state
// verification.
message ConnectionStateData {
option (gogoproto.goproto_getters) = false;
bytes path = 1;
ibc.core.connection.v1.ConnectionEnd connection = 2;
}
// ChannelStateData returns the SignBytes data for channel state
// verification.
message ChannelStateData {
option (gogoproto.goproto_getters) = false;
bytes path = 1;
ibc.core.channel.v1.Channel channel = 2;
}
// PacketCommitmentData returns the SignBytes data for packet commitment
// verification.
message PacketCommitmentData {
bytes path = 1;
bytes commitment = 2;
}
// PacketAcknowledgementData returns the SignBytes data for acknowledgement
// verification.
message PacketAcknowledgementData {
bytes path = 1;
bytes acknowledgement = 2;
}
// PacketReceiptAbsenceData returns the SignBytes data for
// packet receipt absence verification.
message PacketReceiptAbsenceData {
bytes path = 1;
}
// NextSequenceRecvData returns the SignBytes data for verification of the next
// sequence to be received.
message NextSequenceRecvData {
bytes path = 1;
uint64 next_seq_recv = 2 [(gogoproto.moretags) = "yaml:\"next_seq_recv\""];
}

View File

@ -1,111 +0,0 @@
syntax = "proto3";
package ibc.lightclients.tendermint.v1;
option go_package = "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types";
import "tendermint/types/validator.proto";
import "tendermint/types/types.proto";
import "confio/proofs.proto";
import "google/protobuf/duration.proto";
import "google/protobuf/timestamp.proto";
import "ibc/core/client/v1/client.proto";
import "ibc/core/commitment/v1/commitment.proto";
import "gogoproto/gogo.proto";
// ClientState from Tendermint tracks the current validator set, latest height,
// and a possible frozen height.
message ClientState {
option (gogoproto.goproto_getters) = false;
string chain_id = 1;
Fraction trust_level = 2 [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"trust_level\""];
// duration of the period since the LastestTimestamp during which the
// submitted headers are valid for upgrade
google.protobuf.Duration trusting_period = 3
[(gogoproto.nullable) = false, (gogoproto.stdduration) = true, (gogoproto.moretags) = "yaml:\"trusting_period\""];
// duration of the staking unbonding period
google.protobuf.Duration unbonding_period = 4 [
(gogoproto.nullable) = false,
(gogoproto.stdduration) = true,
(gogoproto.moretags) = "yaml:\"unbonding_period\""
];
// defines how much new (untrusted) header's Time can drift into the future.
google.protobuf.Duration max_clock_drift = 5
[(gogoproto.nullable) = false, (gogoproto.stdduration) = true, (gogoproto.moretags) = "yaml:\"max_clock_drift\""];
// Block height when the client was frozen due to a misbehaviour
ibc.core.client.v1.Height frozen_height = 6
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"frozen_height\""];
// Latest height the client was updated to
ibc.core.client.v1.Height latest_height = 7
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"latest_height\""];
// Proof specifications used in verifying counterparty state
repeated ics23.ProofSpec proof_specs = 8 [(gogoproto.moretags) = "yaml:\"proof_specs\""];
// Path at which next upgraded client will be committed.
// Each element corresponds to the key for a single CommitmentProof in the chained proof.
// NOTE: ClientState must stored under `{upgradePath}/{upgradeHeight}/clientState`
// ConsensusState must be stored under `{upgradepath}/{upgradeHeight}/consensusState`
// For SDK chains using the default upgrade module, upgrade_path should be []string{"upgrade", "upgradedIBCState"}`
repeated string upgrade_path = 9 [(gogoproto.moretags) = "yaml:\"upgrade_path\""];
// This flag, when set to true, will allow governance to recover a client
// which has expired
bool allow_update_after_expiry = 10 [(gogoproto.moretags) = "yaml:\"allow_update_after_expiry\""];
// This flag, when set to true, will allow governance to unfreeze a client
// whose chain has experienced a misbehaviour event
bool allow_update_after_misbehaviour = 11 [(gogoproto.moretags) = "yaml:\"allow_update_after_misbehaviour\""];
}
// ConsensusState defines the consensus state from Tendermint.
message ConsensusState {
option (gogoproto.goproto_getters) = false;
// timestamp that corresponds to the block height in which the ConsensusState
// was stored.
google.protobuf.Timestamp timestamp = 1 [(gogoproto.nullable) = false, (gogoproto.stdtime) = true];
// commitment root (i.e app hash)
ibc.core.commitment.v1.MerkleRoot root = 2 [(gogoproto.nullable) = false];
bytes next_validators_hash = 3 [
(gogoproto.casttype) = "github.com/tendermint/tendermint/libs/bytes.HexBytes",
(gogoproto.moretags) = "yaml:\"next_validators_hash\""
];
}
// Misbehaviour is a wrapper over two conflicting Headers
// that implements Misbehaviour interface expected by ICS-02
message Misbehaviour {
option (gogoproto.goproto_getters) = false;
string client_id = 1 [(gogoproto.moretags) = "yaml:\"client_id\""];
Header header_1 = 2 [(gogoproto.customname) = "Header1", (gogoproto.moretags) = "yaml:\"header_1\""];
Header header_2 = 3 [(gogoproto.customname) = "Header2", (gogoproto.moretags) = "yaml:\"header_2\""];
}
// Header defines the Tendermint client consensus Header.
// It encapsulates all the information necessary to update from a trusted
// Tendermint ConsensusState. The inclusion of TrustedHeight and
// TrustedValidators allows this update to process correctly, so long as the
// ConsensusState for the TrustedHeight exists, this removes race conditions
// among relayers The SignedHeader and ValidatorSet are the new untrusted update
// fields for the client. The TrustedHeight is the height of a stored
// ConsensusState on the client that will be used to verify the new untrusted
// header. The Trusted ConsensusState must be within the unbonding period of
// current time in order to correctly verify, and the TrustedValidators must
// hash to TrustedConsensusState.NextValidatorsHash since that is the last
// trusted validator set at the TrustedHeight.
message Header {
.tendermint.types.SignedHeader signed_header = 1
[(gogoproto.embed) = true, (gogoproto.moretags) = "yaml:\"signed_header\""];
.tendermint.types.ValidatorSet validator_set = 2 [(gogoproto.moretags) = "yaml:\"validator_set\""];
ibc.core.client.v1.Height trusted_height = 3
[(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"trusted_height\""];
.tendermint.types.ValidatorSet trusted_validators = 4 [(gogoproto.moretags) = "yaml:\"trusted_validators\""];
}
// Fraction defines the protobuf message type for tmmath.Fraction that only supports positive values.
message Fraction {
uint64 numerator = 1;
uint64 denominator = 2;
}

View File

@ -53,7 +53,7 @@ was sent:
},
{
"key": "_contract_address",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
}
]
}
@ -70,7 +70,7 @@ provide a initial balance in the same `MsgInstantiateContract`. We see the follo
"Attr": [
{
"key": "recipient",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
},
{
"key": "sender",
@ -97,7 +97,7 @@ Here is an example from the escrow contract successfully releasing funds to the
"Attr": [
{
"key": "_contract_address",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
},
{
"key": "action",
@ -131,7 +131,7 @@ was executed (which always appears, while 2 is optional and has information as r
"Attr": [
{
"key": "recipient",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
},
{
"key": "sender",
@ -148,7 +148,7 @@ was executed (which always appears, while 2 is optional and has information as r
"Attr": [
{
"key": "_contract_address",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
},
{
"key": "action",
@ -169,7 +169,7 @@ was executed (which always appears, while 2 is optional and has information as r
},
{
"key": "sender",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
},
{
"key": "amount",
@ -194,7 +194,7 @@ was executed (which always appears, while 2 is optional and has information as r
},
{
"key": "_contract_address",
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
"value": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
}
]
}

View File

@ -12,7 +12,6 @@ import (
const (
firstCodeID = 1
DefaultParamspace = types.DefaultParamspace
ModuleName = types.ModuleName
StoreKey = types.StoreKey
TStoreKey = types.TStoreKey

View File

@ -337,7 +337,7 @@ func hasAccountBalance(cmd *cobra.Command, appState map[string]json.RawMessage,
if err != nil {
return false, err
}
cdc := clientCtx.JSONMarshaler
cdc := clientCtx.Codec
var genBalIterator banktypes.GenesisBalancesIterator
err = genutil.ValidateAccountInGenesis(appState, genBalIterator, sender, coins, cdc)
if err != nil {
@ -392,7 +392,7 @@ func (d DefaultGenesisReader) ReadWasmGenesis(cmd *cobra.Command) (*GenesisData,
var wasmGenesisState types.GenesisState
if appState[types.ModuleName] != nil {
clientCtx := client.GetClientContextFromCmd(cmd)
clientCtx.JSONMarshaler.MustUnmarshalJSON(appState[types.ModuleName], &wasmGenesisState)
clientCtx.Codec.MustUnmarshalJSON(appState[types.ModuleName], &wasmGenesisState)
}
return NewGenesisData(
@ -434,7 +434,7 @@ func (x DefaultGenesisIO) AlterWasmModuleState(cmd *cobra.Command, callback func
return err
}
clientCtx := client.GetClientContextFromCmd(cmd)
wasmGenStateBz, err := clientCtx.JSONMarshaler.MarshalJSON(g.WasmModuleState)
wasmGenStateBz, err := clientCtx.Codec.MarshalJSON(g.WasmModuleState)
if err != nil {
return sdkerrors.Wrap(err, "marshal wasm genesis state")
}

View File

@ -14,6 +14,7 @@ import (
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/testutil"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/cosmos/cosmos-sdk/x/genutil"
@ -303,7 +304,7 @@ func TestInstantiateContractCmd(t *testing.T) {
}
func TestExecuteContractCmd(t *testing.T) {
const firstContractAddress = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6"
const firstContractAddress = "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr"
minimalWasmGenesis := types.GenesisState{
Params: types.DefaultParams(),
}
@ -385,7 +386,7 @@ func TestExecuteContractCmd(t *testing.T) {
},
mutator: func(cmd *cobra.Command) {
// See TestBuildContractAddress in keeper_test.go
cmd.SetArgs([]string{"cosmos1mujpjkwhut9yjw4xueyugc02evfv46y04aervg", `{}`})
cmd.SetArgs([]string{"cosmos1mujpjkwhut9yjw4xueyugc02evfv46y0dtmnz4lh8xxkkdapym9stu5qm8", `{}`})
flagSet := cmd.Flags()
flagSet.Set("run-as", myWellFundedAccount)
},
@ -638,7 +639,7 @@ func executeCmdWithContext(t *testing.T, homeDir string, cmd *cobra.Command) err
require.NoError(t, err)
appCodec := keeper.MakeEncodingConfig(t).Marshaler
serverCtx := server.NewContext(viper.New(), cfg, logger)
clientCtx := client.Context{}.WithJSONMarshaler(appCodec).WithHomeDir(homeDir)
clientCtx := client.Context{}.WithCodec(appCodec).WithHomeDir(homeDir)
ctx := context.Background()
ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx)
@ -650,7 +651,7 @@ func executeCmdWithContext(t *testing.T, homeDir string, cmd *cobra.Command) err
mockIn := testutil.ApplyMockIODiscardOutErr(cmd)
kb, err := keyring.New(sdk.KeyringServiceName(), keyring.BackendTest, homeDir, mockIn)
require.NoError(t, err)
_, err = kb.NewAccount(defaultTestKeyName, testutil.TestMnemonic, "", sdk.FullFundraiserPath, hd.Secp256k1)
_, err = kb.NewAccount(defaultTestKeyName, testdata.TestMnemonic, "", sdk.FullFundraiserPath, hd.Secp256k1)
require.NoError(t, err)
return cmd.ExecuteContext(ctx)
}

View File

@ -413,15 +413,15 @@ func ProposalPinCodesCmd() *cobra.Command {
}
func parsePinCodesArgs(args []string) ([]uint64, error) {
var codeIds []uint64
for _, c := range args {
codeIDs := make([]uint64, len(args))
for i, c := range args {
codeID, err := strconv.ParseUint(c, 10, 64)
if err != nil {
return codeIds, fmt.Errorf("code IDs: %s", err)
return codeIDs, fmt.Errorf("code IDs: %s", err)
}
codeIds = append(codeIds, codeID)
codeIDs[i] = codeID
}
return codeIds, nil
return codeIDs, nil
}
func ProposalUnpinCodesCmd() *cobra.Command {

View File

@ -10,18 +10,18 @@ import (
"github.com/gogo/protobuf/proto"
)
var _ codec.Marshaler = (*ProtoCodec)(nil)
var _ codec.Codec = (*ProtoCodec)(nil)
// ProtoCodec that omits empty values.
// This Marshaler can be used globally when setting up the client context or individually
// for each command via `clientCtx.WithJSONMarshaler(myMarshaler)`.
type ProtoCodec struct {
codec.Marshaler
codec.Codec
interfaceRegistry types.InterfaceRegistry
}
func NewProtoCodec(marshaler codec.Marshaler, registry types.InterfaceRegistry) *ProtoCodec {
return &ProtoCodec{Marshaler: marshaler, interfaceRegistry: registry}
func NewProtoCodec(marshaler codec.Codec, registry types.InterfaceRegistry) *ProtoCodec {
return &ProtoCodec{Codec: marshaler, interfaceRegistry: registry}
}
// MarshalJSON implements JSONMarshaler.MarshalJSON method,

View File

@ -33,7 +33,7 @@ func TestGovRestHandlers(t *testing.T) {
)
encodingConfig := keeper.MakeEncodingConfig(t)
clientCtx := client.Context{}.
WithJSONMarshaler(encodingConfig.Marshaler).
WithCodec(encodingConfig.Marshaler).
WithTxConfig(encodingConfig.TxConfig).
WithLegacyAmino(encodingConfig.Amino).
WithInput(os.Stdin).
@ -173,7 +173,7 @@ func TestGovRestHandlers(t *testing.T) {
"title": "Test Proposal",
"description": "My proposal",
"type": "migrate",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr",
"code_id": "1",
"msg": dict{"foo": "bar"},
"run_as": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz",
@ -189,7 +189,7 @@ func TestGovRestHandlers(t *testing.T) {
"title": "Test Proposal",
"description": "My proposal",
"type": "migrate",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr",
"new_admin": "cosmos100dejzacpanrldpjjwksjm62shqhyss44jf5xz",
"deposit": []dict{{"denom": "ustake", "amount": "10"}},
"proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np",
@ -203,7 +203,7 @@ func TestGovRestHandlers(t *testing.T) {
"title": "Test Proposal",
"description": "My proposal",
"type": "migrate",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6",
"contract": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr",
"deposit": []dict{{"denom": "ustake", "amount": "10"}},
"proposer": "cosmos1ve557a5g9yw2g2z57js3pdmcvd5my6g8ze20np",
"base_req": aBaseReq,

View File

@ -13,8 +13,8 @@ func TestInitGenesis(t *testing.T) {
deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000))
topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000))
creator := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, deposit.Add(deposit...))
fred := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, topUp)
creator := data.faucet.NewFundedAccount(data.ctx, deposit.Add(deposit...)...)
fred := data.faucet.NewFundedAccount(data.ctx, topUp...)
h := data.module.Route().Handler()
q := data.module.LegacyQuerierHandler(nil)

View File

@ -3,13 +3,15 @@ package wasm
import (
"math"
ibcexported "github.com/cosmos/ibc-go/v2/modules/core/exported"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
porttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/05-port/types"
host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
porttypes "github.com/cosmos/ibc-go/v2/modules/core/05-port/types"
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
types "github.com/CosmWasm/wasmd/x/wasm/types"
)
@ -219,27 +221,42 @@ func toWasmVMChannel(portID, channelID string, channelInfo channeltypes.Channel)
func (i IBCHandler) OnRecvPacket(
ctx sdk.Context,
packet channeltypes.Packet,
) (*sdk.Result, []byte, error) {
relayer sdk.AccAddress,
) ibcexported.Acknowledgement {
contractAddr, err := ContractFromPortID(packet.DestinationPort)
if err != nil {
return nil, nil, sdkerrors.Wrapf(err, "contract port id")
return channeltypes.NewErrorAcknowledgement(sdkerrors.Wrapf(err, "contract port id").Error())
}
msg := wasmvmtypes.IBCPacketReceiveMsg{Packet: newIBCPacket(packet)}
ack, err := i.keeper.OnRecvPacket(ctx, contractAddr, msg)
if err != nil {
return nil, nil, err
return channeltypes.NewErrorAcknowledgement(err.Error())
}
return ContractConfirmStateAck(ack)
}
return &sdk.Result{ // the response is ignored
Events: ctx.EventManager().Events().ToABCIEvents(),
}, ack, nil
var _ ibcexported.Acknowledgement = ContractConfirmStateAck{}
type ContractConfirmStateAck []byte
func (w ContractConfirmStateAck) Success() bool {
return true // always commit state
}
func (w ContractConfirmStateAck) Acknowledgement() []byte {
return w
}
// OnAcknowledgementPacket implements the IBCModule interface
func (i IBCHandler) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes.Packet, acknowledgement []byte) (*sdk.Result, error) {
func (i IBCHandler) OnAcknowledgementPacket(
ctx sdk.Context,
packet channeltypes.Packet,
acknowledgement []byte,
relayer sdk.AccAddress,
) error {
contractAddr, err := ContractFromPortID(packet.SourcePort)
if err != nil {
return nil, sdkerrors.Wrapf(err, "contract port id")
return sdkerrors.Wrapf(err, "contract port id")
}
err = i.keeper.OnAckPacket(ctx, contractAddr, wasmvmtypes.IBCPacketAckMsg{
@ -247,31 +264,34 @@ func (i IBCHandler) OnAcknowledgementPacket(ctx sdk.Context, packet channeltypes
OriginalPacket: newIBCPacket(packet),
})
if err != nil {
return nil, err
return sdkerrors.Wrap(err, "on ack")
}
return &sdk.Result{
Events: ctx.EventManager().Events().ToABCIEvents(),
}, nil
return nil
}
// OnTimeoutPacket implements the IBCModule interface
func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet) (*sdk.Result, error) {
func (i IBCHandler) OnTimeoutPacket(ctx sdk.Context, packet channeltypes.Packet, relayer sdk.AccAddress) error {
contractAddr, err := ContractFromPortID(packet.SourcePort)
if err != nil {
return nil, sdkerrors.Wrapf(err, "contract port id")
return sdkerrors.Wrapf(err, "contract port id")
}
msg := wasmvmtypes.IBCPacketTimeoutMsg{Packet: newIBCPacket(packet)}
err = i.keeper.OnTimeoutPacket(ctx, contractAddr, msg)
if err != nil {
return nil, err
return sdkerrors.Wrap(err, "on timeout")
}
return nil
}
return &sdk.Result{
Events: ctx.EventManager().Events().ToABCIEvents(),
}, nil
func (i IBCHandler) NegotiateAppVersion(
ctx sdk.Context,
order channeltypes.Order,
connectionID string,
portID string,
counterparty channeltypes.Counterparty,
proposedVersion string,
) (version string, err error) {
return proposedVersion, nil // accept all
}
func newIBCPacket(packet channeltypes.Packet) wasmvmtypes.IBCPacket {

View File

@ -3,13 +3,15 @@ package wasm_test
import (
"testing"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
ibcexported "github.com/cosmos/cosmos-sdk/x/ibc/core/exported"
"github.com/stretchr/testify/assert"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
ibctesting "github.com/cosmos/ibc-go/v2/testing"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
"github.com/stretchr/testify/require"
"github.com/CosmWasm/wasmd/x/wasm/ibctesting"
wasmibctesting "github.com/CosmWasm/wasmd/x/wasm/ibctesting"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
)
@ -22,9 +24,9 @@ func TestIBCReflectContract(t *testing.T) {
// "ibc_reflect" sends a submessage to "reflect" which is returned as submessage.
var (
coordinator = ibctesting.NewCoordinator(t, 2, nil, nil)
chainA = coordinator.GetChain(ibctesting.GetChainID(0))
chainB = coordinator.GetChain(ibctesting.GetChainID(1))
coordinator = wasmibctesting.NewCoordinator(t, 2)
chainA = coordinator.GetChain(wasmibctesting.GetChainID(0))
chainB = coordinator.GetChain(wasmibctesting.GetChainID(1))
)
coordinator.CommitBlock(chainA, chainB)
@ -43,11 +45,24 @@ func TestIBCReflectContract(t *testing.T) {
sourcePortID = chainA.ContractInfo(sendContractAddr).IBCPortID
counterpartPortID = chainB.ContractInfo(reflectContractAddr).IBCPortID
)
clientA, clientB, connA, connB := coordinator.SetupClientConnections(chainA, chainB, ibcexported.Tendermint)
connA.NextChannelVersion = "ibc-reflect-v1"
connB.NextChannelVersion = "ibc-reflect-v1"
// flip instantiation so that we do not run into https://github.com/cosmos/cosmos-sdk/issues/8334
channelA, channelB := coordinator.CreateChannel(chainA, chainB, connA, connB, sourcePortID, counterpartPortID, channeltypes.ORDERED)
coordinator.CommitBlock(chainA, chainB)
coordinator.UpdateTime()
require.Equal(t, chainA.CurrentHeader.Time, chainB.CurrentHeader.Time)
path := wasmibctesting.NewPath(chainA, chainB)
path.EndpointA.ChannelConfig = &ibctesting.ChannelConfig{
PortID: sourcePortID,
Version: "ibc-reflect-v1",
Order: channeltypes.ORDERED,
}
path.EndpointB.ChannelConfig = &ibctesting.ChannelConfig{
PortID: counterpartPortID,
Version: "ibc-reflect-v1",
Order: channeltypes.ORDERED,
}
coordinator.SetupConnections(path)
coordinator.CreateChannels(path)
// TODO: query both contracts directly to ensure they have registered the proper connection
// (and the chainB has created a reflect contract)
@ -69,13 +84,13 @@ func TestIBCReflectContract(t *testing.T) {
// ensure the expected packet was prepared, and relay it
require.Equal(t, 1, len(chainA.PendingSendPackets))
require.Equal(t, 0, len(chainB.PendingSendPackets))
err := coordinator.RelayAndAckPendingPackets(chainA, chainB, clientA, clientB)
err := coordinator.RelayAndAckPendingPackets(path)
require.NoError(t, err)
require.Equal(t, 0, len(chainA.PendingSendPackets))
require.Equal(t, 0, len(chainB.PendingSendPackets))
// let's query the source contract and make sure it registered an address
query := ReflectSendQueryMsg{Account: &AccountQuery{ChannelID: channelA.ID}}
query := ReflectSendQueryMsg{Account: &AccountQuery{ChannelID: path.EndpointA.ChannelID}}
var account AccountResponse
err = chainA.SmartQuery(sendContractAddr.String(), query, &account)
require.NoError(t, err)
@ -83,15 +98,13 @@ func TestIBCReflectContract(t *testing.T) {
require.Empty(t, account.RemoteBalance)
// close channel
coordinator.CloseChannel(chainA, chainB, channelA, channelB)
coordinator.CloseChannel(path)
// let's query the source contract and make sure it registered an address
account = AccountResponse{}
err = chainA.SmartQuery(sendContractAddr.String(), query, &account)
require.Error(t, err)
assert.Contains(t, err.Error(), "not found")
_ = clientB
}
type ReflectSendQueryMsg struct {

View File

@ -4,8 +4,8 @@ import (
"testing"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
clienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
"github.com/stretchr/testify/assert"
)

View File

@ -3,24 +3,10 @@ package ibctesting
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"testing"
"time"
wasmd "github.com/CosmWasm/wasmd/app"
"github.com/CosmWasm/wasmd/x/wasm/keeper"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmprotoversion "github.com/tendermint/tendermint/proto/tendermint/version"
tmtypes "github.com/tendermint/tendermint/types"
tmversion "github.com/tendermint/tendermint/version"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1"
@ -29,57 +15,31 @@ import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper"
capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types"
connectiontypes "github.com/cosmos/cosmos-sdk/x/ibc/core/03-connection/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/23-commitment/types"
host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
"github.com/cosmos/cosmos-sdk/x/ibc/core/exported"
"github.com/cosmos/cosmos-sdk/x/ibc/core/types"
ibctmtypes "github.com/cosmos/cosmos-sdk/x/ibc/light-clients/07-tendermint/types"
ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing"
"github.com/cosmos/cosmos-sdk/x/ibc/testing/mock"
stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper"
"github.com/cosmos/cosmos-sdk/x/staking/teststaking"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
)
clienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
commitmenttypes "github.com/cosmos/ibc-go/v2/modules/core/23-commitment/types"
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
"github.com/cosmos/ibc-go/v2/modules/core/exported"
ibckeeper "github.com/cosmos/ibc-go/v2/modules/core/keeper"
"github.com/cosmos/ibc-go/v2/modules/core/types"
ibctmtypes "github.com/cosmos/ibc-go/v2/modules/light-clients/07-tendermint/types"
ibctesting "github.com/cosmos/ibc-go/v2/testing"
"github.com/cosmos/ibc-go/v2/testing/mock"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmprotoversion "github.com/tendermint/tendermint/proto/tendermint/version"
tmtypes "github.com/tendermint/tendermint/types"
tmversion "github.com/tendermint/tendermint/version"
const (
// Default params constants used to create a TM client
TrustingPeriod time.Duration = time.Hour * 24 * 7 * 2
UnbondingPeriod time.Duration = time.Hour * 24 * 7 * 3
MaxClockDrift time.Duration = time.Second * 10
DefaultDelayPeriod uint64 = 0
DefaultChannelVersion = ibctransfertypes.Version
InvalidID = "IDisInvalid"
ConnectionIDPrefix = "conn"
ChannelIDPrefix = "chan"
TransferPort = ibctransfertypes.ModuleName
MockPort = mock.ModuleName
// used for testing UpdateClientProposal
Title = "title"
Description = "description"
)
var (
DefaultOpenInitVersion *connectiontypes.Version
// Default params variables used to create a TM client
DefaultTrustLevel ibctmtypes.Fraction = ibctmtypes.DefaultTrustLevel
TestHash = tmhash.Sum([]byte("TESTING HASH"))
TestCoin = sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100))
UpgradePath = []string{"upgrade", "upgradedIBCState"}
ConnectionVersion = connectiontypes.ExportedVersionsToProto(connectiontypes.GetCompatibleVersions())[0]
MockAcknowledgement = mock.MockAcknowledgement
MockCommitment = mock.MockCommitment
wasmd "github.com/CosmWasm/wasmd/app"
"github.com/CosmWasm/wasmd/x/wasm"
)
// TestChain is a testing struct that wraps a simapp with the last TM Header, the current ABCI
@ -90,13 +50,14 @@ var (
type TestChain struct {
t *testing.T
App *wasmd.WasmApp
Coordinator *Coordinator
App ibctesting.TestingApp
ChainID string
LastHeader *ibctmtypes.Header // header for last block height committed
CurrentHeader tmproto.Header // header for current block height
QueryServer types.QueryServer
TxConfig client.TxConfig
Codec codec.BinaryMarshaler
Codec codec.BinaryCodec
Vals *tmtypes.ValidatorSet
Signers []tmtypes.PrivValidator
@ -104,10 +65,6 @@ type TestChain struct {
senderPrivKey cryptotypes.PrivKey
SenderAccount authtypes.AccountI
// IBC specific helpers
ClientIDs []string // ClientID's used on this chain
Connections []*ibctesting.TestConnection // track connectionID's created for this chain
PendingSendPackets []channeltypes.Packet
PendingAckPackets []PacketAck
}
@ -125,7 +82,7 @@ type PacketAck struct {
//
// Time management is handled by the Coordinator in order to ensure synchrony between chains.
// Each update of any chain increments the block header time for all chains by 5 seconds.
func NewTestChain(t *testing.T, chainID string, opt ...keeper.Option) *TestChain {
func NewTestChain(t *testing.T, coord *Coordinator, chainID string, opts ...wasm.Option) *TestChain {
// generate validator private/public key
privVal := mock.NewPV()
pubKey, err := privVal.GetPubKey()
@ -139,68 +96,63 @@ func NewTestChain(t *testing.T, chainID string, opt ...keeper.Option) *TestChain
// generate genesis account
senderPrivKey := secp256k1.GenPrivKey()
acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0)
amount, ok := sdk.NewIntFromString("10000000000000000000")
require.True(t, ok)
balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)),
}
// make a temp dir for the wasm files for this chain
tempDir, err := ioutil.TempDir("", "wasm")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(tempDir) })
app := wasmd.SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, opt, balance)
app := NewTestingAppDecorator(t, wasmd.SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, opts, balance))
// create current header and call begin block
header := tmproto.Header{
ChainID: chainID,
Height: 1,
Time: globalStartTime,
Time: coord.CurrentTime.UTC(),
}
txConfig := wasmd.MakeEncodingConfig().TxConfig
txConfig := app.GetTxConfig()
testScope := wasmd.NewTestSupport(t, app)
ibcKeeper := testScope.IBCKeeper()
// create an account to send transactions from
chain := &TestChain{
t: t,
Coordinator: coord,
ChainID: chainID,
App: app,
CurrentHeader: header,
QueryServer: ibcKeeper,
QueryServer: app.GetIBCKeeper(),
TxConfig: txConfig,
Codec: testScope.AppCodec(),
Codec: app.AppCodec(),
Vals: valSet,
Signers: signers,
senderPrivKey: senderPrivKey,
SenderAccount: acc,
ClientIDs: make([]string, 0),
Connections: make([]*ibctesting.TestConnection, 0),
}
portKeeper := &ibcKeeper.PortKeeper
cap := portKeeper.BindPort(chain.GetContext(), MockPort)
err = testScope.ScopedWasmIBCKeeper().ClaimCapability(chain.GetContext(), cap, host.PortPath(MockPort))
require.NoError(t, err)
chain.NextBlock()
coord.CommitBlock(chain)
return chain
}
// GetContext returns the current context for the application.
func (chain *TestChain) GetContext() sdk.Context {
return chain.App.BaseApp.NewContext(false, chain.CurrentHeader)
return chain.App.GetBaseApp().NewContext(false, chain.CurrentHeader)
}
// QueryProof performs an abci query with the given key and returns the proto encoded merkle proof
// for the query and the height at which the proof will succeed on a tendermint verifier.
func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height) {
return chain.QueryProofAtHeight(key, chain.App.LastBlockHeight())
}
// QueryProof performs an abci query with the given key and returns the proto encoded merkle proof
// for the query and the height at which the proof will succeed on a tendermint verifier.
func (chain *TestChain) QueryProofAtHeight(key []byte, height int64) ([]byte, clienttypes.Height) {
res := chain.App.Query(abci.RequestQuery{
Path: fmt.Sprintf("store/%s/key", host.StoreKey),
Height: chain.App.LastBlockHeight() - 1,
Height: height - 1,
Data: key,
Prove: true,
})
@ -208,7 +160,7 @@ func (chain *TestChain) QueryProof(key []byte) ([]byte, clienttypes.Height) {
merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps)
require.NoError(chain.t, err)
proof, err := chain.Codec.MarshalBinaryBare(&merkleProof)
proof, err := chain.App.AppCodec().Marshal(&merkleProof)
require.NoError(chain.t, err)
revision := clienttypes.ParseChainID(chain.ChainID)
@ -232,7 +184,7 @@ func (chain *TestChain) QueryUpgradeProof(key []byte, height uint64) ([]byte, cl
merkleProof, err := commitmenttypes.ConvertProofs(res.ProofOps)
require.NoError(chain.t, err)
proof, err := chain.Codec.MarshalBinaryBare(&merkleProof)
proof, err := chain.App.AppCodec().Marshal(&merkleProof)
require.NoError(chain.t, err)
revision := clienttypes.ParseChainID(chain.ChainID)
@ -243,19 +195,6 @@ func (chain *TestChain) QueryUpgradeProof(key []byte, height uint64) ([]byte, cl
return proof, clienttypes.NewHeight(revision, uint64(res.Height+1))
}
// QueryClientStateProof performs and abci query for a client state
// stored with a given clientID and returns the ClientState along with the proof
func (chain *TestChain) QueryClientStateProof(clientID string) (exported.ClientState, []byte) {
// retrieve client state to provide proof for
clientState, found := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ClientKeeper.GetClientState(chain.GetContext(), clientID)
require.True(chain.t, found)
clientKey := host.FullClientStateKey(clientID)
proofClient, _ := chain.QueryProof(clientKey)
return clientState, proofClient
}
// QueryConsensusStateProof performs an abci query for a consensus state
// stored on the given clientID. The proof and consensusHeight are returned.
func (chain *TestChain) QueryConsensusStateProof(clientID string) ([]byte, clienttypes.Height) {
@ -290,7 +229,6 @@ func (chain *TestChain) NextBlock() {
}
chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader})
}
// sendMsgs delivers a transaction through the application without returning the result.
@ -303,10 +241,14 @@ func (chain *TestChain) sendMsgs(msgs ...sdk.Msg) error {
// number and updates the TestChain's headers. It returns the result and error if one
// occurred.
func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) {
_, r, err := wasmd.SignCheckDeliver(
// ensure the chain has the latest time
chain.Coordinator.UpdateTimeForChain(chain)
_, r, err := wasmd.SignAndDeliver(
chain.t,
chain.TxConfig,
chain.App.BaseApp,
chain.App.GetBaseApp(),
chain.GetContext().BlockHeader(),
msgs,
chain.ChainID,
@ -318,7 +260,7 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) {
return nil, err
}
// SignCheckDeliver calls app.Commit()
// SignAndDeliver calls app.Commit()
chain.NextBlock()
// increment sequence for successful transaction execution
@ -327,7 +269,14 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) {
return nil, err
}
// TODO: also return acks needed to send
chain.Coordinator.IncrementTime()
chain.captureIBCEvents(r)
return r, nil
}
func (chain *TestChain) captureIBCEvents(r *sdk.Result) {
toSend := getSendPackets(r.Events)
if len(toSend) > 0 {
// Keep a queue on the chain that we can relay in tests
@ -338,95 +287,12 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) {
// Keep a queue on the chain that we can relay in tests
chain.PendingAckPackets = append(chain.PendingAckPackets, toAck...)
}
return r, nil
}
func getSendPackets(evts []abci.Event) []channeltypes.Packet {
var res []channeltypes.Packet
for _, evt := range evts {
if evt.Type == "send_packet" {
packet := parsePacketFromEvent(evt)
res = append(res, packet)
}
}
return res
}
func getAckPackets(evts []abci.Event) []PacketAck {
var res []PacketAck
for _, evt := range evts {
if evt.Type == "write_acknowledgement" {
packet := parsePacketFromEvent(evt)
ack := PacketAck{
Packet: packet,
Ack: []byte(getField(evt, "packet_ack")),
}
res = append(res, ack)
}
}
return res
}
// Used for various debug statements above when needed... do not remove
// func showEvent(evt abci.Event) {
// fmt.Printf("evt.Type: %s\n", evt.Type)
// for _, attr := range evt.Attributes {
// fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value))
// }
//}
func parsePacketFromEvent(evt abci.Event) channeltypes.Packet {
return channeltypes.Packet{
Sequence: getUintField(evt, "packet_sequence"),
SourcePort: getField(evt, "packet_src_port"),
SourceChannel: getField(evt, "packet_src_channel"),
DestinationPort: getField(evt, "packet_dst_port"),
DestinationChannel: getField(evt, "packet_dst_channel"),
Data: []byte(getField(evt, "packet_data")),
TimeoutHeight: parseTimeoutHeight(getField(evt, "packet_timeout_height")),
TimeoutTimestamp: getUintField(evt, "packet_timeout_timestamp"),
}
}
// return the value for the attribute with the given name
func getField(evt abci.Event, key string) string {
for _, attr := range evt.Attributes {
if string(attr.Key) == key {
return string(attr.Value)
}
}
return ""
}
func getUintField(evt abci.Event, key string) uint64 {
raw := getField(evt, key)
return toUint64(raw)
}
func toUint64(raw string) uint64 {
if raw == "" {
return 0
}
i, err := strconv.ParseUint(raw, 10, 64)
if err != nil {
panic(err)
}
return i
}
func parseTimeoutHeight(raw string) clienttypes.Height {
chunks := strings.Split(raw, "-")
return clienttypes.Height{
RevisionNumber: toUint64(chunks[0]),
RevisionHeight: toUint64(chunks[1]),
}
}
// GetClientState retrieves the client state for the provided clientID. The client is
// expected to exist otherwise testing will fail.
func (chain *TestChain) GetClientState(clientID string) exported.ClientState {
clientState, found := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ClientKeeper.GetClientState(chain.GetContext(), clientID)
clientState, found := chain.App.GetIBCKeeper().ClientKeeper.GetClientState(chain.GetContext(), clientID)
require.True(chain.t, found)
return clientState
@ -435,48 +301,30 @@ func (chain *TestChain) GetClientState(clientID string) exported.ClientState {
// GetConsensusState retrieves the consensus state for the provided clientID and height.
// It will return a success boolean depending on if consensus state exists or not.
func (chain *TestChain) GetConsensusState(clientID string, height exported.Height) (exported.ConsensusState, bool) {
return wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ClientKeeper.GetClientConsensusState(chain.GetContext(), clientID, height)
return chain.App.GetIBCKeeper().ClientKeeper.GetClientConsensusState(chain.GetContext(), clientID, height)
}
// GetValsAtHeight will return the validator set of the chain at a given height. It will return
// a success boolean depending on if the validator set exists or not at that height.
func (chain *TestChain) GetValsAtHeight(height int64) (*tmtypes.ValidatorSet, bool) {
histInfo, ok := wasmd.NewTestSupport(chain.t, chain.App).StakingKeeper().GetHistoricalInfo(chain.GetContext(), height)
histInfo, ok := chain.App.GetStakingKeeper().GetHistoricalInfo(chain.GetContext(), height)
if !ok {
return nil, false
}
valSet := stakingtypes.Validators(histInfo.Valset)
tmValidators, err := teststaking.ToTmValidators(valSet)
tmValidators, err := teststaking.ToTmValidators(valSet, sdk.DefaultPowerReduction)
if err != nil {
panic(err)
}
return tmtypes.NewValidatorSet(tmValidators), true
}
// GetConnection retrieves an IBC Connection for the provided TestConnection. The
// connection is expected to exist otherwise testing will fail.
func (chain *TestChain) GetConnection(testConnection *ibctesting.TestConnection) connectiontypes.ConnectionEnd {
connection, found := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ConnectionKeeper.GetConnection(chain.GetContext(), testConnection.ID)
require.True(chain.t, found)
return connection
}
// GetChannel retrieves an IBC Channel for the provided ibctesting.TestChannel. The channel
// is expected to exist otherwise testing will fail.
func (chain *TestChain) GetChannel(testChannel ibctesting.TestChannel) channeltypes.Channel {
channel, found := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ChannelKeeper.GetChannel(chain.GetContext(), testChannel.PortID, testChannel.ID)
require.True(chain.t, found)
return channel
}
// GetAcknowledgement retrieves an acknowledgement for the provided packet. If the
// acknowledgement does not exist then testing will fail.
func (chain *TestChain) GetAcknowledgement(packet exported.PacketI) []byte {
ack, found := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ChannelKeeper.GetPacketAcknowledgement(chain.GetContext(), packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
ack, found := chain.App.GetIBCKeeper().ChannelKeeper.GetPacketAcknowledgement(chain.GetContext(), packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
require.True(chain.t, found)
return ack
@ -484,138 +332,23 @@ func (chain *TestChain) GetAcknowledgement(packet exported.PacketI) []byte {
// GetPrefix returns the prefix for used by a chain in connection creation
func (chain *TestChain) GetPrefix() commitmenttypes.MerklePrefix {
return commitmenttypes.NewMerklePrefix(wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ConnectionKeeper.GetCommitmentPrefix().Bytes())
}
// NewClientID appends a new clientID string in the format:
// ClientFor<counterparty-chain-id><index>
func (chain *TestChain) NewClientID(clientType string) string {
clientID := fmt.Sprintf("%s-%s", clientType, strconv.Itoa(len(chain.ClientIDs)))
chain.ClientIDs = append(chain.ClientIDs, clientID)
return clientID
}
// AddTestConnection appends a new TestConnection which contains references
// to the connection id, client id and counterparty client id.
func (chain *TestChain) AddTestConnection(clientID, counterpartyClientID string) *ibctesting.TestConnection {
conn := chain.ConstructNextTestConnection(clientID, counterpartyClientID)
chain.Connections = append(chain.Connections, conn)
return conn
}
// ConstructNextTestConnection constructs the next test connection to be
// created given a clientID and counterparty clientID. The connection id
// format: <chainID>-conn<index>
func (chain *TestChain) ConstructNextTestConnection(clientID, counterpartyClientID string) *ibctesting.TestConnection {
connectionID := connectiontypes.FormatConnectionIdentifier(uint64(len(chain.Connections)))
return &ibctesting.TestConnection{
ID: connectionID,
ClientID: clientID,
NextChannelVersion: DefaultChannelVersion,
CounterpartyClientID: counterpartyClientID,
}
}
// GetFirstTestConnection returns the first test connection for a given clientID.
// The connection may or may not exist in the chain state.
func (chain *TestChain) GetFirstTestConnection(clientID, counterpartyClientID string) *ibctesting.TestConnection {
if len(chain.Connections) > 0 {
return chain.Connections[0]
}
return chain.ConstructNextTestConnection(clientID, counterpartyClientID)
}
// AddTestChannel Add ibctesting.TestChannel appends a new ibctesting.TestChannel which contains references to the port and channel ID
// used for channel creation and interaction. See 'Next ibctesting.TestChannel' for channel ID naming format.
func (chain *TestChain) AddTestChannel(conn *ibctesting.TestConnection, portID string) ibctesting.TestChannel {
channel := chain.NextChannel(conn, portID)
conn.Channels = append(conn.Channels, channel)
return channel
}
// NextChannel Next ibctesting.TestChannel returns the next test channel to be created on this connection, but does not
// add it to the list of created channels. This function is expected to be used when the caller
// has not created the associated channel in app state, but would still like to refer to the
// non-existent channel usually to test for its non-existence.
//
// channel ID format: <connectionid>-chan<channel-index>
//
// The port is passed in by the caller.
func (chain *TestChain) NextChannel(conn *ibctesting.TestConnection, portID string) ibctesting.TestChannel {
nextChanSeq := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ChannelKeeper.GetNextChannelSequence(chain.GetContext())
channelID := channeltypes.FormatChannelIdentifier(nextChanSeq)
return ibctesting.TestChannel{
PortID: portID,
ID: channelID,
ClientID: conn.ClientID,
CounterpartyClientID: conn.CounterpartyClientID,
Version: conn.NextChannelVersion,
}
}
// ConstructMsgCreateClient constructs a message to create a new client state (tendermint or solomachine).
// NOTE: a solo machine client will be created with an empty diversifier.
func (chain *TestChain) ConstructMsgCreateClient(counterparty *TestChain, clientID string, clientType string) *clienttypes.MsgCreateClient {
var (
clientState exported.ClientState
consensusState exported.ConsensusState
)
switch clientType {
case exported.Tendermint:
height := counterparty.LastHeader.GetHeight().(clienttypes.Height)
clientState = ibctmtypes.NewClientState(
counterparty.ChainID, DefaultTrustLevel, TrustingPeriod, UnbondingPeriod, MaxClockDrift,
height, commitmenttypes.GetSDKSpecs(), UpgradePath, false, false,
)
consensusState = counterparty.LastHeader.ConsensusState()
case exported.Solomachine:
solo := ibctesting.NewSolomachine(chain.t, chain.Codec, clientID, "", 1)
clientState = solo.ClientState()
consensusState = solo.ConsensusState()
default:
chain.t.Fatalf("unsupported client state type %s", clientType)
}
msg, err := clienttypes.NewMsgCreateClient(
clientState, consensusState, chain.SenderAccount.GetAddress(),
)
require.NoError(chain.t, err)
return msg
}
// CreateTMClient will construct and execute a 07-tendermint MsgCreateClient. A counterparty
// client will be created on the (target) chain.
func (chain *TestChain) CreateTMClient(counterparty *TestChain, clientID string) error {
// construct MsgCreateClient using counterparty
msg := chain.ConstructMsgCreateClient(counterparty, clientID, exported.Tendermint)
return chain.sendMsgs(msg)
}
// UpdateTMClient will construct and execute a 07-tendermint MsgUpdateClient. The counterparty
// client will be updated on the (target) chain. UpdateTMClient mocks the relayer flow
// necessary for updating a Tendermint client.
func (chain *TestChain) UpdateTMClient(counterparty *TestChain, clientID string) error {
header, err := chain.ConstructUpdateTMClientHeader(counterparty, clientID)
require.NoError(chain.t, err)
msg, err := clienttypes.NewMsgUpdateClient(
clientID, header,
chain.SenderAccount.GetAddress(),
)
require.NoError(chain.t, err)
return chain.sendMsgs(msg)
return commitmenttypes.NewMerklePrefix(chain.App.GetIBCKeeper().ConnectionKeeper.GetCommitmentPrefix().Bytes())
}
// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the
// light client on the source chain.
func (chain *TestChain) ConstructUpdateTMClientHeader(counterparty *TestChain, clientID string) (*ibctmtypes.Header, error) {
return chain.ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty, clientID, clienttypes.ZeroHeight())
}
// ConstructUpdateTMClientHeader will construct a valid 07-tendermint Header to update the
// light client on the source chain.
func (chain *TestChain) ConstructUpdateTMClientHeaderWithTrustedHeight(counterparty *TestChain, clientID string, trustedHeight clienttypes.Height) (*ibctmtypes.Header, error) {
header := counterparty.LastHeader
// Relayer must query for LatestHeight on client to get TrustedHeight
trustedHeight := chain.GetClientState(clientID).GetLatestHeight().(clienttypes.Height)
// Relayer must query for LatestHeight on client to get TrustedHeight if the trusted height is not set
if trustedHeight.IsZero() {
trustedHeight = chain.GetClientState(clientID).GetLatestHeight().(clienttypes.Height)
}
var (
tmTrustedVals *tmtypes.ValidatorSet
ok bool
@ -652,7 +385,7 @@ func (chain *TestChain) ConstructUpdateTMClientHeader(counterparty *TestChain, c
// ExpireClient fast forwards the chain's block time by the provided amount of time which will
// expire any clients with a trusting period less than or equal to this amount of time.
func (chain *TestChain) ExpireClient(amount time.Duration) {
chain.CurrentHeader.Time = chain.CurrentHeader.Time.Add(amount)
chain.Coordinator.IncrementTimeBy(amount)
}
// CurrentTMClientHeader creates a TM header using the current header parameters
@ -753,105 +486,21 @@ func CreateSortedSignerArray(altPrivVal, suitePrivVal tmtypes.PrivValidator,
}
}
// ConnectionOpenInit will construct and execute a MsgConnectionOpenInit.
func (chain *TestChain) ConnectionOpenInit(
counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
) error {
msg := connectiontypes.NewMsgConnectionOpenInit(
connection.ClientID,
connection.CounterpartyClientID,
counterparty.GetPrefix(), DefaultOpenInitVersion, DefaultDelayPeriod,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
}
// ConnectionOpenTry will construct and execute a MsgConnectionOpenTry.
func (chain *TestChain) ConnectionOpenTry(
counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
) error {
counterpartyClient, proofClient := counterparty.QueryClientStateProof(counterpartyConnection.ClientID)
connectionKey := host.ConnectionKey(counterpartyConnection.ID)
proofInit, proofHeight := counterparty.QueryProof(connectionKey)
proofConsensus, consensusHeight := counterparty.QueryConsensusStateProof(counterpartyConnection.ClientID)
msg := connectiontypes.NewMsgConnectionOpenTry(
"", connection.ClientID, // does not support handshake continuation
counterpartyConnection.ID, counterpartyConnection.ClientID,
counterpartyClient, counterparty.GetPrefix(), []*connectiontypes.Version{ConnectionVersion}, DefaultDelayPeriod,
proofInit, proofClient, proofConsensus,
proofHeight, consensusHeight,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
}
// ConnectionOpenAck will construct and execute a MsgConnectionOpenAck.
func (chain *TestChain) ConnectionOpenAck(
counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
) error {
counterpartyClient, proofClient := counterparty.QueryClientStateProof(counterpartyConnection.ClientID)
connectionKey := host.ConnectionKey(counterpartyConnection.ID)
proofTry, proofHeight := counterparty.QueryProof(connectionKey)
proofConsensus, consensusHeight := counterparty.QueryConsensusStateProof(counterpartyConnection.ClientID)
msg := connectiontypes.NewMsgConnectionOpenAck(
connection.ID, counterpartyConnection.ID, counterpartyClient, // testing doesn't use flexible selection
proofTry, proofClient, proofConsensus,
proofHeight, consensusHeight,
ConnectionVersion,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
}
// ConnectionOpenConfirm will construct and execute a MsgConnectionOpenConfirm.
func (chain *TestChain) ConnectionOpenConfirm(
counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
) error {
connectionKey := host.ConnectionKey(counterpartyConnection.ID)
proof, height := counterparty.QueryProof(connectionKey)
msg := connectiontypes.NewMsgConnectionOpenConfirm(
connection.ID,
proof, height,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
}
// CreatePortCapability binds and claims a capability for the given portID if it does not
// already exist. This function will fail testing on any resulting error.
// NOTE: only creation of a capbility for a transfer or mock port is supported
// Other applications must bind to the port in InitGenesis or modify this code.
func (chain *TestChain) CreatePortCapability(portID string) {
func (chain *TestChain) CreatePortCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID string) {
// check if the portId is already binded, if not bind it
_, ok := chain.TestSupport().ScopeIBCKeeper().GetCapability(chain.GetContext(), host.PortPath(portID))
_, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), host.PortPath(portID))
if !ok {
// create capability using the IBC capability keeper
cap, err := chain.TestSupport().ScopeIBCKeeper().NewCapability(chain.GetContext(), host.PortPath(portID))
cap, err := chain.App.GetScopedIBCKeeper().NewCapability(chain.GetContext(), host.PortPath(portID))
require.NoError(chain.t, err)
switch portID {
case MockPort:
// claim capability using the mock capability keeper
err = wasmd.NewTestSupport(chain.t, chain.App).ScopedWasmIBCKeeper().ClaimCapability(chain.GetContext(), cap, host.PortPath(portID))
require.NoError(chain.t, err)
case TransferPort:
// claim capability using the transfer capability keeper
err = chain.TestSupport().ScopedTransferKeeper().ClaimCapability(chain.GetContext(), cap, host.PortPath(portID))
require.NoError(chain.t, err)
default:
panic(fmt.Sprintf("unsupported ibc testing package port ID %s", portID))
}
// claim capability using the scopedKeeper
err = scopedKeeper.ClaimCapability(chain.GetContext(), cap, host.PortPath(portID))
require.NoError(chain.t, err)
}
chain.App.Commit()
@ -862,22 +511,23 @@ func (chain *TestChain) CreatePortCapability(portID string) {
// GetPortCapability returns the port capability for the given portID. The capability must
// exist, otherwise testing will fail.
func (chain *TestChain) GetPortCapability(portID string) *capabilitytypes.Capability {
cap, ok := chain.TestSupport().ScopeIBCKeeper().GetCapability(chain.GetContext(), host.PortPath(portID))
cap, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), host.PortPath(portID))
require.True(chain.t, ok)
return cap
}
// CreateChannelCapability binds and claims a capability for the given portID and channelID
// if it does not already exist. This function will fail testing on any resulting error.
func (chain *TestChain) CreateChannelCapability(portID, channelID string) {
// if it does not already exist. This function will fail testing on any resulting error. The
// scoped keeper passed in will claim the new capability.
func (chain *TestChain) CreateChannelCapability(scopedKeeper capabilitykeeper.ScopedKeeper, portID, channelID string) {
capName := host.ChannelCapabilityPath(portID, channelID)
// check if the portId is already binded, if not bind it
_, ok := chain.TestSupport().ScopeIBCKeeper().GetCapability(chain.GetContext(), capName)
_, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), capName)
if !ok {
cap, err := chain.TestSupport().ScopeIBCKeeper().NewCapability(chain.GetContext(), capName)
cap, err := chain.App.GetScopedIBCKeeper().NewCapability(chain.GetContext(), capName)
require.NoError(chain.t, err)
err = chain.TestSupport().ScopedTransferKeeper().ClaimCapability(chain.GetContext(), cap, capName)
err = scopedKeeper.ClaimCapability(chain.GetContext(), cap, capName)
require.NoError(chain.t, err)
}
@ -889,139 +539,55 @@ func (chain *TestChain) CreateChannelCapability(portID, channelID string) {
// GetChannelCapability returns the channel capability for the given portID and channelID.
// The capability must exist, otherwise testing will fail.
func (chain *TestChain) GetChannelCapability(portID, channelID string) *capabilitytypes.Capability {
cap, ok := chain.TestSupport().ScopeIBCKeeper().GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID))
cap, ok := chain.App.GetScopedIBCKeeper().GetCapability(chain.GetContext(), host.ChannelCapabilityPath(portID, channelID))
require.True(chain.t, ok)
return cap
}
// ChanOpenInit will construct and execute a MsgChannelOpenInit.
func (chain *TestChain) ChanOpenInit(
ch, counterparty ibctesting.TestChannel,
order channeltypes.Order,
connectionID string,
) error {
msg := channeltypes.NewMsgChannelOpenInit(
ch.PortID,
ch.Version, order, []string{connectionID},
counterparty.PortID,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
func (chain *TestChain) Balance(acc sdk.AccAddress, denom string) sdk.Coin {
return chain.GetTestSupport().BankKeeper().GetBalance(chain.GetContext(), acc, denom)
}
// ChanOpenTry will construct and execute a MsgChannelOpenTry.
func (chain *TestChain) ChanOpenTry(
counterparty *TestChain,
ch, counterpartyCh ibctesting.TestChannel,
order channeltypes.Order,
connectionID string,
) error {
proof, height := counterparty.QueryProof(host.ChannelKey(counterpartyCh.PortID, counterpartyCh.ID))
msg := channeltypes.NewMsgChannelOpenTry(
ch.PortID, "", // does not support handshake continuation
ch.Version, order, []string{connectionID},
counterpartyCh.PortID, counterpartyCh.ID, counterpartyCh.Version,
proof, height,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
func (chain *TestChain) AllBalances(acc sdk.AccAddress) sdk.Coins {
return chain.GetTestSupport().BankKeeper().GetAllBalances(chain.GetContext(), acc)
}
// ChanOpenAck will construct and execute a MsgChannelOpenAck.
func (chain *TestChain) ChanOpenAck(
counterparty *TestChain,
ch, counterpartyCh ibctesting.TestChannel,
) error {
proof, height := counterparty.QueryProof(host.ChannelKey(counterpartyCh.PortID, counterpartyCh.ID))
msg := channeltypes.NewMsgChannelOpenAck(
ch.PortID, ch.ID,
counterpartyCh.ID, counterpartyCh.Version, // testing doesn't use flexible selection
proof, height,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
func (chain TestChain) GetTestSupport() *wasmd.TestSupport {
return chain.App.(*TestingAppDecorator).TestSupport()
}
// ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm.
func (chain *TestChain) ChanOpenConfirm(
counterparty *TestChain,
ch, counterpartyCh ibctesting.TestChannel,
) error {
proof, height := counterparty.QueryProof(host.ChannelKey(counterpartyCh.PortID, counterpartyCh.ID))
var _ ibctesting.TestingApp = TestingAppDecorator{}
msg := channeltypes.NewMsgChannelOpenConfirm(
ch.PortID, ch.ID,
proof, height,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
type TestingAppDecorator struct {
*wasmd.WasmApp
t *testing.T
}
// ChanCloseInit will construct and execute a MsgChannelCloseInit.
//
// NOTE: does not work with ibc-transfer module
func (chain *TestChain) ChanCloseInit(
counterparty *TestChain,
channel ibctesting.TestChannel,
) error {
msg := channeltypes.NewMsgChannelCloseInit(
channel.PortID, channel.ID,
chain.SenderAccount.GetAddress(),
)
return chain.sendMsgs(msg)
func NewTestingAppDecorator(t *testing.T, wasmApp *wasmd.WasmApp) *TestingAppDecorator {
return &TestingAppDecorator{WasmApp: wasmApp, t: t}
}
// GetPacketData returns a ibc-transfer marshalled packet to be used for
// callback testing.
func (chain *TestChain) GetPacketData(counterparty *TestChain) []byte {
packet := ibctransfertypes.FungibleTokenPacketData{
Denom: TestCoin.Denom,
Amount: TestCoin.Amount.Uint64(),
Sender: chain.SenderAccount.GetAddress().String(),
Receiver: counterparty.SenderAccount.GetAddress().String(),
}
return packet.GetBytes()
func (a TestingAppDecorator) GetBaseApp() *baseapp.BaseApp {
return a.TestSupport().GetBaseApp()
}
// SendPacket simulates sending a packet through the channel keeper. No message needs to be
// passed since this call is made from a module.
func (chain *TestChain) SendPacket(
packet exported.PacketI,
) error {
channelCap := chain.GetChannelCapability(packet.GetSourcePort(), packet.GetSourceChannel())
// no need to send message, acting as a module
err := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ChannelKeeper.SendPacket(chain.GetContext(), channelCap, packet)
if err != nil {
return err
}
// commit changes
chain.App.Commit()
chain.NextBlock()
return nil
func (a TestingAppDecorator) GetStakingKeeper() stakingkeeper.Keeper {
return a.TestSupport().StakingKeeper()
}
// WriteAcknowledgement simulates writing an acknowledgement to the chain.
func (chain *TestChain) WriteAcknowledgement(
packet exported.PacketI,
) error {
channelCap := chain.GetChannelCapability(packet.GetDestPort(), packet.GetDestChannel())
// no need to send message, acting as a handler
err := wasmd.NewTestSupport(chain.t, chain.App).IBCKeeper().ChannelKeeper.WriteAcknowledgement(chain.GetContext(), channelCap, packet, TestHash)
if err != nil {
return err
}
// commit changes
chain.App.Commit()
chain.NextBlock()
return nil
func (a TestingAppDecorator) GetIBCKeeper() *ibckeeper.Keeper {
return a.TestSupport().IBCKeeper()
}
func (a TestingAppDecorator) GetScopedIBCKeeper() capabilitykeeper.ScopedKeeper {
return a.TestSupport().ScopeIBCKeeper()
}
func (a TestingAppDecorator) GetTxConfig() client.TxConfig {
return a.TestSupport().GetTxConfig()
}
func (a TestingAppDecorator) TestSupport() *wasmd.TestSupport {
return wasmd.NewTestSupport(a.t, a.WasmApp)
}

View File

@ -6,21 +6,19 @@ import (
"testing"
"time"
sdk "github.com/cosmos/cosmos-sdk/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
"github.com/cosmos/cosmos-sdk/x/ibc/core/exported"
ibctesting "github.com/cosmos/cosmos-sdk/x/ibc/testing"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
ibctesting "github.com/cosmos/ibc-go/v2/testing"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/CosmWasm/wasmd/x/wasm/keeper"
wasmkeeper "github.com/CosmWasm/wasmd/x/wasm/keeper"
)
const ChainIDPrefix = "testchain"
var (
ChainIDPrefix = "testchain"
globalStartTime = time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
globalStartTime = time.Date(2020, 12, 4, 10, 30, 0, 0, time.UTC)
TimeIncrement = time.Second * 5
)
@ -29,401 +27,152 @@ var (
type Coordinator struct {
t *testing.T
Chains map[string]*TestChain
CurrentTime time.Time
Chains map[string]*TestChain
}
// NewCoordinator initializes Coordinator with N TestChain's
func NewCoordinator(t *testing.T, n int, opts ...[]keeper.Option) *Coordinator {
func NewCoordinator(t *testing.T, n int, opts ...[]wasmkeeper.Option) *Coordinator {
chains := make(map[string]*TestChain)
if len(opts) != 0 && len(opts) != n {
t.Fatalf("opts not matching number of instances: %d", len(opts))
coord := &Coordinator{
t: t,
CurrentTime: globalStartTime,
}
for i := 0; i < n; i++ {
chainID := GetChainID(i)
var iOpts []keeper.Option
if len(opts) != 0 {
iOpts = opts[i]
var x []wasmkeeper.Option
if len(opts) > i {
x = opts[i]
}
chains[chainID] = NewTestChain(t, chainID, iOpts...)
chains[chainID] = NewTestChain(t, coord, chainID, x...)
}
return &Coordinator{
t: t,
Chains: chains,
coord.Chains = chains
return coord
}
// IncrementTime iterates through all the TestChain's and increments their current header time
// by 5 seconds.
//
// CONTRACT: this function must be called after every Commit on any TestChain.
func (coord *Coordinator) IncrementTime() {
coord.IncrementTimeBy(TimeIncrement)
}
// IncrementTimeBy iterates through all the TestChain's and increments their current header time
// by specified time.
func (coord *Coordinator) IncrementTimeBy(increment time.Duration) {
coord.CurrentTime = coord.CurrentTime.Add(increment).UTC()
coord.UpdateTime()
}
// UpdateTime updates all clocks for the TestChains to the current global time.
func (coord *Coordinator) UpdateTime() {
for _, chain := range coord.Chains {
coord.UpdateTimeForChain(chain)
}
}
// UpdateTimeForChain updates the clock for a specific chain.
func (coord *Coordinator) UpdateTimeForChain(chain *TestChain) {
chain.CurrentHeader.Time = coord.CurrentTime.UTC()
chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader})
}
// Setup constructs a TM client, connection, and channel on both chains provided. It will
// fail if any error occurs. The clientID's, TestConnections, and TestChannels are returned
// for both chains. The channels created are connected to the ibc-transfer application.
func (coord *Coordinator) Setup(
chainA, chainB *TestChain, order channeltypes.Order,
) (string, string, *ibctesting.TestConnection, *ibctesting.TestConnection, ibctesting.TestChannel, ibctesting.TestChannel) {
clientA, clientB, connA, connB := coord.SetupClientConnections(chainA, chainB, exported.Tendermint)
func (coord *Coordinator) Setup(path *Path) {
coord.SetupConnections(path)
// channels can also be referenced through the returned connections
channelA, channelB := coord.CreateMockChannels(chainA, chainB, connA, connB, order)
return clientA, clientB, connA, connB, channelA, channelB
coord.CreateChannels(path)
}
// SetupClients is a helper function to create clients on both chains. It assumes the
// caller does not anticipate any errors.
func (coord *Coordinator) SetupClients(
chainA, chainB *TestChain,
clientType string,
) (string, string) {
clientA, err := coord.CreateClient(chainA, chainB, clientType)
func (coord *Coordinator) SetupClients(path *Path) {
err := path.EndpointA.CreateClient()
require.NoError(coord.t, err)
clientB, err := coord.CreateClient(chainB, chainA, clientType)
err = path.EndpointB.CreateClient()
require.NoError(coord.t, err)
return clientA, clientB
}
// SetupClientConnections is a helper function to create clients and the appropriate
// connections on both the source and counterparty chain. It assumes the caller does not
// anticipate any errors.
func (coord *Coordinator) SetupClientConnections(
chainA, chainB *TestChain,
clientType string,
) (string, string, *ibctesting.TestConnection, *ibctesting.TestConnection) {
func (coord *Coordinator) SetupConnections(path *Path) {
coord.SetupClients(path)
clientA, clientB := coord.SetupClients(chainA, chainB, clientType)
connA, connB := coord.CreateConnection(chainA, chainB, clientA, clientB)
return clientA, clientB, connA, connB
}
// CreateClient creates a counterparty client on the source chain and returns the clientID.
func (coord *Coordinator) CreateClient(
source, counterparty *TestChain,
clientType string,
) (clientID string, err error) {
coord.CommitBlock(source, counterparty)
clientID = source.NewClientID(clientType)
switch clientType {
case exported.Tendermint:
err = source.CreateTMClient(counterparty, clientID)
default:
err = fmt.Errorf("client type %s is not supported", clientType)
}
if err != nil {
return "", err
}
coord.IncrementTime()
return clientID, nil
}
// UpdateClient updates a counterparty client on the source chain.
func (coord *Coordinator) UpdateClient(
source, counterparty *TestChain,
clientID string,
clientType string,
) (err error) {
coord.CommitBlock(source, counterparty)
switch clientType {
case exported.Tendermint:
err = source.UpdateTMClient(counterparty, clientID)
default:
err = fmt.Errorf("client type %s is not supported", clientType)
}
if err != nil {
return err
}
coord.IncrementTime()
return nil
coord.CreateConnections(path)
}
// CreateConnection constructs and executes connection handshake messages in order to create
// OPEN channels on chainA and chainB. The connection information of for chainA and chainB
// are returned within a TestConnection struct. The function expects the connections to be
// successfully opened otherwise testing will fail.
func (coord *Coordinator) CreateConnection(
chainA, chainB *TestChain,
clientA, clientB string,
) (*ibctesting.TestConnection, *ibctesting.TestConnection) {
func (coord *Coordinator) CreateConnections(path *Path) {
connA, connB, err := coord.ConnOpenInit(chainA, chainB, clientA, clientB)
err := path.EndpointA.ConnOpenInit()
require.NoError(coord.t, err)
err = coord.ConnOpenTry(chainB, chainA, connB, connA)
err = path.EndpointB.ConnOpenTry()
require.NoError(coord.t, err)
err = coord.ConnOpenAck(chainA, chainB, connA, connB)
err = path.EndpointA.ConnOpenAck()
require.NoError(coord.t, err)
err = coord.ConnOpenConfirm(chainB, chainA, connB, connA)
err = path.EndpointB.ConnOpenConfirm()
require.NoError(coord.t, err)
return connA, connB
// ensure counterparty is up to date
err = path.EndpointA.UpdateClient()
require.NoError(coord.t, err)
}
// CreateMockChannels constructs and executes channel handshake messages to create OPEN
// channels that use a mock application module that returns nil on all callbacks. This
// function is expects the channels to be successfully opened otherwise testing will
// fail.
func (coord *Coordinator) CreateMockChannels(
chainA, chainB *TestChain,
connA, connB *ibctesting.TestConnection,
order channeltypes.Order,
) (ibctesting.TestChannel, ibctesting.TestChannel) {
return coord.CreateChannel(chainA, chainB, connA, connB, MockPort, MockPort, order)
func (coord *Coordinator) CreateMockChannels(path *Path) {
path.EndpointA.ChannelConfig.PortID = ibctesting.MockPort
path.EndpointB.ChannelConfig.PortID = ibctesting.MockPort
coord.CreateChannels(path)
}
// CreateTransferChannels constructs and executes channel handshake messages to create OPEN
// ibc-transfer channels on chainA and chainB. The function expects the channels to be
// successfully opened otherwise testing will fail.
func (coord *Coordinator) CreateTransferChannels(
chainA, chainB *TestChain,
connA, connB *ibctesting.TestConnection,
order channeltypes.Order,
) (ibctesting.TestChannel, ibctesting.TestChannel) {
return coord.CreateChannel(chainA, chainB, connA, connB, TransferPort, TransferPort, order)
func (coord *Coordinator) CreateTransferChannels(path *Path) {
path.EndpointA.ChannelConfig.PortID = ibctesting.TransferPort
path.EndpointB.ChannelConfig.PortID = ibctesting.TransferPort
coord.CreateChannels(path)
}
// CreateChannel constructs and executes channel handshake messages in order to create
// OPEN channels on chainA and chainB. The function expects the channels to be successfully
// opened otherwise testing will fail.
func (coord *Coordinator) CreateChannel(
chainA, chainB *TestChain,
connA, connB *ibctesting.TestConnection,
sourcePortID, counterpartyPortID string,
order channeltypes.Order,
) (ibctesting.TestChannel, ibctesting.TestChannel) {
channelA, channelB, err := coord.ChanOpenInit(chainA, chainB, connA, connB, sourcePortID, counterpartyPortID, order)
func (coord *Coordinator) CreateChannels(path *Path) {
err := path.EndpointA.ChanOpenInit()
require.NoError(coord.t, err)
err = coord.ChanOpenTry(chainB, chainA, channelB, channelA, connB, order)
err = path.EndpointB.ChanOpenTry()
require.NoError(coord.t, err)
err = coord.ChanOpenAck(chainA, chainB, channelA, channelB)
err = path.EndpointA.ChanOpenAck()
require.NoError(coord.t, err)
err = coord.ChanOpenConfirm(chainB, chainA, channelB, channelA)
err = path.EndpointB.ChanOpenConfirm()
require.NoError(coord.t, err)
return channelA, channelB
}
// SendPacket sends a packet through the channel keeper on the source chain and updates the
// counterparty client for the source chain.
func (coord *Coordinator) SendPacket(
source, counterparty *TestChain,
packet exported.PacketI,
counterpartyClientID string,
) error {
if err := source.SendPacket(packet); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyClientID, exported.Tendermint,
)
}
// RecvPacket receives a channel packet on the counterparty chain and updates
// the client on the source chain representing the counterparty.
func (coord *Coordinator) RecvPacket(
source, counterparty *TestChain,
sourceClient string,
packet channeltypes.Packet,
) error {
// get proof of packet commitment on source
packetKey := host.PacketCommitmentKey(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())
proof, proofHeight := source.QueryProof(packetKey)
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(source, counterparty)
recvMsg := channeltypes.NewMsgRecvPacket(packet, proof, proofHeight, counterparty.SenderAccount.GetAddress())
// receive on counterparty and update source client
return coord.SendMsgs(counterparty, source, sourceClient, []sdk.Msg{recvMsg})
}
// TimeoutPacket returns the package to source chain to let the IBC app revert any operation.
func (coord *Coordinator) TimeoutPacket(
source, counterparty *TestChain,
counterpartyClient string,
packet channeltypes.Packet,
) error {
// get proof of packet unreceived on dest
packetKey := host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
proofUnreceived, proofHeight := counterparty.QueryProof(packetKey)
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(source, counterparty)
timeoutMsg := channeltypes.NewMsgTimeout(packet, packet.Sequence, proofUnreceived, proofHeight, source.SenderAccount.GetAddress())
return coord.SendMsgs(source, counterparty, counterpartyClient, []sdk.Msg{timeoutMsg})
}
// WriteAcknowledgement writes an acknowledgement to the channel keeper on the source chain and updates the
// counterparty client for the source chain.
func (coord *Coordinator) WriteAcknowledgement(
source, counterparty *TestChain,
packet exported.PacketI,
counterpartyClientID string,
) error {
if err := source.WriteAcknowledgement(packet); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyClientID, exported.Tendermint,
)
}
// AcknowledgePacket acknowledges on the source chain the packet received on
// the counterparty chain and updates the client on the counterparty representing
// the source chain.
// TODO: add a query for the acknowledgement by events
// - https://github.com/cosmos/cosmos-sdk/issues/6509
func (coord *Coordinator) AcknowledgePacket(
source, counterparty *TestChain,
counterpartyClient string,
packet channeltypes.Packet, ack []byte,
) error {
// get proof of acknowledgement on counterparty
packetKey := host.PacketAcknowledgementKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
proof, proofHeight := counterparty.QueryProof(packetKey)
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(source, counterparty)
ackMsg := channeltypes.NewMsgAcknowledgement(packet, ack, proof, proofHeight, source.SenderAccount.GetAddress())
return coord.SendMsgs(source, counterparty, counterpartyClient, []sdk.Msg{ackMsg})
}
// RelayPacket receives a channel packet on counterparty, queries the ack
// and acknowledges the packet on source. The clients are updated as needed.
func (coord *Coordinator) RelayPacket(
source, counterparty *TestChain,
sourceClient, counterpartyClient string,
packet channeltypes.Packet, ack []byte,
) error {
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(counterparty)
if err := coord.RecvPacket(source, counterparty, sourceClient, packet); err != nil {
return err
}
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(source)
return coord.AcknowledgePacket(source, counterparty, counterpartyClient, packet, ack)
}
// IncrementTime iterates through all the TestChain's and increments their current header time
// by 5 seconds.
//
// CONTRACT: this function must be called after every commit on any TestChain.
func (coord *Coordinator) IncrementTime() {
for _, chain := range coord.Chains {
chain.CurrentHeader.Time = chain.CurrentHeader.Time.Add(TimeIncrement)
chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader})
}
}
// IncrementTimeBy iterates through all the TestChain's and increments their current header time
// by specified time.
func (coord *Coordinator) IncrementTimeBy(increment time.Duration) {
for _, chain := range coord.Chains {
chain.CurrentHeader.Time = chain.CurrentHeader.Time.Add(increment)
chain.App.BeginBlock(abci.RequestBeginBlock{Header: chain.CurrentHeader})
}
}
// SendMsg delivers a single provided message to the chain. The counterparty
// client is update with the new source consensus state.
func (coord *Coordinator) SendMsg(source, counterparty *TestChain, counterpartyClientID string, msg sdk.Msg) error {
return coord.SendMsgs(source, counterparty, counterpartyClientID, []sdk.Msg{msg})
}
// SendMsgs delivers the provided messages to the chain. The counterparty
// client is updated with the new source consensus state.
func (coord *Coordinator) SendMsgs(source, counterparty *TestChain, counterpartyClientID string, msgs []sdk.Msg) error {
if err := source.sendMsgs(msgs...); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyClientID, exported.Tendermint,
)
}
func (coord *Coordinator) RelayAndAckPendingPackets(src, dest *TestChain, srcClientID, dstClientID string) error {
// get all the packet to relay src->dest
toSend := src.PendingSendPackets
src.PendingSendPackets = nil
fmt.Printf("Relay %d Packets A->B\n", len(toSend))
// send this to the other side
coord.IncrementTime()
coord.CommitBlock(src)
err := coord.UpdateClient(dest, src, dstClientID, exported.Tendermint)
if err != nil {
return err
}
for _, packet := range toSend {
err := coord.RecvPacket(src, dest, srcClientID, packet)
if err != nil {
return err
}
}
// get all the acks to relay dest->src
toAck := dest.PendingAckPackets
dest.PendingAckPackets = nil
// TODO: assert >= len(toSend)?
fmt.Printf("Ack %d Packets B->A\n", len(toAck))
// send the ack back from dest -> src
coord.IncrementTime()
coord.CommitBlock(dest)
err = coord.UpdateClient(src, dest, srcClientID, exported.Tendermint)
if err != nil {
return err
}
for _, ack := range toAck {
err = coord.AcknowledgePacket(src, dest, srcClientID, ack.Packet, ack.Ack)
if err != nil {
return err
}
}
return nil
// ensure counterparty is up to date
err = path.EndpointA.UpdateClient()
require.NoError(coord.t, err)
}
// GetChain returns the TestChain using the given chainID and returns an error if it does
@ -460,345 +209,135 @@ func (coord *Coordinator) CommitNBlocks(chain *TestChain, n uint64) {
}
}
// ConnOpenInit initializes a connection on the source chain with the state INIT
// ConnOpenInitOnBothChains initializes a connection on both endpoints with the state INIT
// using the OpenInit handshake call.
//
// NOTE: The counterparty testing connection will be created even if it is not created in the
// application state.
func (coord *Coordinator) ConnOpenInit(
source, counterparty *TestChain,
clientID, counterpartyClientID string,
) (*ibctesting.TestConnection, *ibctesting.TestConnection, error) {
sourceConnection := source.AddTestConnection(clientID, counterpartyClientID)
counterpartyConnection := counterparty.AddTestConnection(counterpartyClientID, clientID)
// initialize connection on source
if err := source.ConnectionOpenInit(counterparty, sourceConnection, counterpartyConnection); err != nil {
return sourceConnection, counterpartyConnection, err
}
coord.IncrementTime()
// update source client on counterparty connection
if err := coord.UpdateClient(
counterparty, source,
counterpartyClientID, exported.Tendermint,
); err != nil {
return sourceConnection, counterpartyConnection, err
}
return sourceConnection, counterpartyConnection, nil
}
// ConnOpenInitOnBothChains initializes a connection on the source chain with the state INIT
// using the OpenInit handshake call.
func (coord *Coordinator) ConnOpenInitOnBothChains(
source, counterparty *TestChain,
clientID, counterpartyClientID string,
) (*ibctesting.TestConnection, *ibctesting.TestConnection, error) {
sourceConnection := source.AddTestConnection(clientID, counterpartyClientID)
counterpartyConnection := counterparty.AddTestConnection(counterpartyClientID, clientID)
// initialize connection on source
if err := source.ConnectionOpenInit(counterparty, sourceConnection, counterpartyConnection); err != nil {
return sourceConnection, counterpartyConnection, err
}
coord.IncrementTime()
// initialize connection on counterparty
if err := counterparty.ConnectionOpenInit(source, counterpartyConnection, sourceConnection); err != nil {
return sourceConnection, counterpartyConnection, err
}
coord.IncrementTime()
// update counterparty client on source connection
if err := coord.UpdateClient(
source, counterparty,
clientID, exported.Tendermint,
); err != nil {
return sourceConnection, counterpartyConnection, err
}
// update source client on counterparty connection
if err := coord.UpdateClient(
counterparty, source,
counterpartyClientID, exported.Tendermint,
); err != nil {
return sourceConnection, counterpartyConnection, err
}
return sourceConnection, counterpartyConnection, nil
}
// ConnOpenTry initializes a connection on the source chain with the state TRYOPEN
// using the OpenTry handshake call.
func (coord *Coordinator) ConnOpenTry(
source, counterparty *TestChain,
sourceConnection, counterpartyConnection *ibctesting.TestConnection,
) error {
// initialize TRYOPEN connection on source
if err := source.ConnectionOpenTry(counterparty, sourceConnection, counterpartyConnection); err != nil {
func (coord *Coordinator) ConnOpenInitOnBothChains(path *Path) error {
if err := path.EndpointA.ConnOpenInit(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyConnection.ClientID, exported.Tendermint,
)
}
// ConnOpenAck initializes a connection on the source chain with the state OPEN
// using the OpenAck handshake call.
func (coord *Coordinator) ConnOpenAck(
source, counterparty *TestChain,
sourceConnection, counterpartyConnection *ibctesting.TestConnection,
) error {
// set OPEN connection on source using OpenAck
if err := source.ConnectionOpenAck(counterparty, sourceConnection, counterpartyConnection); err != nil {
if err := path.EndpointB.ConnOpenInit(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyConnection.ClientID, exported.Tendermint,
)
}
// ConnOpenConfirm initializes a connection on the source chain with the state OPEN
// using the OpenConfirm handshake call.
func (coord *Coordinator) ConnOpenConfirm(
source, counterparty *TestChain,
sourceConnection, counterpartyConnection *ibctesting.TestConnection,
) error {
if err := source.ConnectionOpenConfirm(counterparty, sourceConnection, counterpartyConnection); err != nil {
if err := path.EndpointA.UpdateClient(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
counterpartyConnection.ClientID, exported.Tendermint,
)
}
// ChanOpenInit initializes a channel on the source chain with the state INIT
// using the OpenInit handshake call.
//
// NOTE: The counterparty testing channel will be created even if it is not created in the
// application state.
func (coord *Coordinator) ChanOpenInit(
source, counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
sourcePortID, counterpartyPortID string,
order channeltypes.Order,
) (ibctesting.TestChannel, ibctesting.TestChannel, error) {
sourceChannel := source.AddTestChannel(connection, sourcePortID)
counterpartyChannel := counterparty.AddTestChannel(counterpartyConnection, counterpartyPortID)
// NOTE: only creation of a capability for a transfer or mock port is supported
// Other applications must bind to the port in InitGenesis or modify this code.
source.CreatePortCapability(sourceChannel.PortID)
coord.IncrementTime()
// initialize channel on source
if err := source.ChanOpenInit(sourceChannel, counterpartyChannel, order, connection.ID); err != nil {
return sourceChannel, counterpartyChannel, err
}
coord.IncrementTime()
// update source client on counterparty connection
if err := coord.UpdateClient(
counterparty, source,
counterpartyConnection.ClientID, exported.Tendermint,
); err != nil {
return sourceChannel, counterpartyChannel, err
if err := path.EndpointB.UpdateClient(); err != nil {
return err
}
return sourceChannel, counterpartyChannel, nil
return nil
}
// ChanOpenInitOnBothChains initializes a channel on the source chain and counterparty chain
// with the state INIT using the OpenInit handshake call.
func (coord *Coordinator) ChanOpenInitOnBothChains(
source, counterparty *TestChain,
connection, counterpartyConnection *ibctesting.TestConnection,
sourcePortID, counterpartyPortID string,
order channeltypes.Order,
) (ibctesting.TestChannel, ibctesting.TestChannel, error) {
sourceChannel := source.AddTestChannel(connection, sourcePortID)
counterpartyChannel := counterparty.AddTestChannel(counterpartyConnection, counterpartyPortID)
func (coord *Coordinator) ChanOpenInitOnBothChains(path *Path) error {
// NOTE: only creation of a capability for a transfer or mock port is supported
// Other applications must bind to the port in InitGenesis or modify this code.
source.CreatePortCapability(sourceChannel.PortID)
counterparty.CreatePortCapability(counterpartyChannel.PortID)
coord.IncrementTime()
// initialize channel on source
if err := source.ChanOpenInit(sourceChannel, counterpartyChannel, order, connection.ID); err != nil {
return sourceChannel, counterpartyChannel, err
}
coord.IncrementTime()
// initialize channel on counterparty
if err := counterparty.ChanOpenInit(counterpartyChannel, sourceChannel, order, counterpartyConnection.ID); err != nil {
return sourceChannel, counterpartyChannel, err
}
coord.IncrementTime()
// update counterparty client on source connection
if err := coord.UpdateClient(
source, counterparty,
connection.ClientID, exported.Tendermint,
); err != nil {
return sourceChannel, counterpartyChannel, err
}
// update source client on counterparty connection
if err := coord.UpdateClient(
counterparty, source,
counterpartyConnection.ClientID, exported.Tendermint,
); err != nil {
return sourceChannel, counterpartyChannel, err
}
return sourceChannel, counterpartyChannel, nil
}
// ChanOpenTry initializes a channel on the source chain with the state TRYOPEN
// using the OpenTry handshake call.
func (coord *Coordinator) ChanOpenTry(
source, counterparty *TestChain,
sourceChannel, counterpartyChannel ibctesting.TestChannel,
connection *ibctesting.TestConnection,
order channeltypes.Order,
) error {
// initialize channel on source
if err := source.ChanOpenTry(counterparty, sourceChannel, counterpartyChannel, order, connection.ID); err != nil {
if err := path.EndpointA.ChanOpenInit(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
connection.CounterpartyClientID, exported.Tendermint,
)
}
// ChanOpenAck initializes a channel on the source chain with the state OPEN
// using the OpenAck handshake call.
func (coord *Coordinator) ChanOpenAck(
source, counterparty *TestChain,
sourceChannel, counterpartyChannel ibctesting.TestChannel,
) error {
if err := source.ChanOpenAck(counterparty, sourceChannel, counterpartyChannel); err != nil {
if err := path.EndpointB.ChanOpenInit(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
sourceChannel.CounterpartyClientID, exported.Tendermint,
)
}
// ChanOpenConfirm initializes a channel on the source chain with the state OPEN
// using the OpenConfirm handshake call.
func (coord *Coordinator) ChanOpenConfirm(
source, counterparty *TestChain,
sourceChannel, counterpartyChannel ibctesting.TestChannel,
) error {
if err := source.ChanOpenConfirm(counterparty, sourceChannel, counterpartyChannel); err != nil {
if err := path.EndpointA.UpdateClient(); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
sourceChannel.CounterpartyClientID, exported.Tendermint,
)
if err := path.EndpointB.UpdateClient(); err != nil {
return err
}
return nil
}
func (coord *Coordinator) CloseChannel(
source, counterparty *TestChain,
channel, counterpartyChannel ibctesting.TestChannel,
) {
err := source.ChanCloseInit(counterparty, channel)
// from A to B
func (coord *Coordinator) RelayAndAckPendingPackets(path *Path) error {
// get all the packet to relay src->dest
src := path.EndpointA
dest := path.EndpointB
toSend := src.Chain.PendingSendPackets
coord.t.Logf("Relay %d Packets A->B\n", len(toSend))
// send this to the other side
coord.IncrementTime()
coord.CommitBlock(src.Chain)
err := dest.UpdateClient()
if err != nil {
return err
}
for _, packet := range toSend {
err = dest.RecvPacket(packet)
if err != nil {
return err
}
}
src.Chain.PendingSendPackets = nil
// get all the acks to relay dest->src
toAck := dest.Chain.PendingAckPackets
// TODO: assert >= len(toSend)?
coord.t.Logf("Ack %d Packets B->A\n", len(toAck))
// send the ack back from dest -> src
coord.IncrementTime()
coord.CommitBlock(dest.Chain)
err = src.UpdateClient()
if err != nil {
return err
}
for _, ack := range toAck {
err = src.AcknowledgePacket(ack.Packet, ack.Ack)
if err != nil {
return err
}
}
dest.Chain.PendingAckPackets = nil
return nil
}
// TimeoutPendingPackets returns the package to source chain to let the IBC app revert any operation.
// from A to A
func (coord *Coordinator) TimeoutPendingPackets(path *Path) error {
src := path.EndpointA
dest := path.EndpointB
toSend := src.Chain.PendingSendPackets
coord.t.Logf("Timeout %d Packets A->A\n", len(toSend))
if err := src.UpdateClient(); err != nil {
return err
}
// Increment time and commit block so that 5 second delay period passes between send and receive
coord.IncrementTime()
coord.CommitBlock(src.Chain, dest.Chain)
for _, packet := range toSend {
// get proof of packet unreceived on dest
packetKey := host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
proofUnreceived, proofHeight := dest.QueryProof(packetKey)
timeoutMsg := channeltypes.NewMsgTimeout(packet, packet.Sequence, proofUnreceived, proofHeight, src.Chain.SenderAccount.GetAddress().String())
err := src.Chain.sendMsgs(timeoutMsg)
if err != nil {
return err
}
}
src.Chain.PendingSendPackets = nil
dest.Chain.PendingAckPackets = nil
return nil
}
// CloseChannel close channel on both sides
func (coord *Coordinator) CloseChannel(path *Path) {
err := path.EndpointA.ChanCloseInit()
require.NoError(coord.t, err)
coord.IncrementTime()
err = coord.UpdateClient(counterparty, source, counterpartyChannel.ClientID, exported.Tendermint)
err = path.EndpointB.UpdateClient()
require.NoError(coord.t, err)
err = coord.ChanCloseConfirm(source, counterparty, channel, counterpartyChannel)
err = path.EndpointB.ChanCloseConfirm()
require.NoError(coord.t, err)
}
// ChanCloseInit closes a channel on the source chain resulting in the channels state
// being set to CLOSED.
//
// NOTE: does not work with ibc-transfer module
func (coord *Coordinator) ChanCloseInit(
source, counterparty *TestChain,
channel ibctesting.TestChannel,
) error {
if err := source.ChanCloseInit(counterparty, channel); err != nil {
return err
}
coord.IncrementTime()
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
channel.CounterpartyClientID, exported.Tendermint,
)
}
// ChanCloseConfirm closes a channel on the counterparty chain resulting in the channels state
// being set to CLOSED.
//
// NOTE: does not work with ibc-transfer module
func (coord *Coordinator) ChanCloseConfirm(
source, counterparty *TestChain,
channel, counterpartyChannel ibctesting.TestChannel,
) error {
channelKey := host.ChannelKey(channel.PortID, channel.ID)
proof, proofHeight := source.QueryProof(channelKey)
msg := channeltypes.NewMsgChannelCloseConfirm(
counterpartyChannel.PortID, counterpartyChannel.ID,
proof, proofHeight,
counterparty.SenderAccount.GetAddress(),
)
return coord.SendMsgs(counterparty, source, counterpartyChannel.CounterpartyClientID, []sdk.Msg{msg})
}
// SetChannelClosed sets a channel state to CLOSED.
func (coord *Coordinator) SetChannelClosed(
source, counterparty *TestChain,
testChannel ibctesting.TestChannel,
) error {
channel := source.GetChannel(testChannel)
channel.State = channeltypes.CLOSED
source.TestSupport().
IBCKeeper().ChannelKeeper.SetChannel(source.GetContext(), testChannel.PortID, testChannel.ID, channel)
coord.CommitBlock(source)
// update source client on counterparty connection
return coord.UpdateClient(
counterparty, source,
testChannel.CounterpartyClientID, exported.Tendermint,
)
}

View File

@ -0,0 +1,544 @@
package ibctesting
import (
"fmt"
ibctesting "github.com/cosmos/ibc-go/v2/testing"
// sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
clienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
connectiontypes "github.com/cosmos/ibc-go/v2/modules/core/03-connection/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
commitmenttypes "github.com/cosmos/ibc-go/v2/modules/core/23-commitment/types"
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
"github.com/cosmos/ibc-go/v2/modules/core/exported"
ibctmtypes "github.com/cosmos/ibc-go/v2/modules/light-clients/07-tendermint/types"
)
// Endpoint is a which represents a channel endpoint and its associated
// client and connections. It contains client, connection, and channel
// configuration parameters. Endpoint functions will utilize the parameters
// set in the configuration structs when executing IBC messages.
type Endpoint struct {
Chain *TestChain
Counterparty *Endpoint
ClientID string
ConnectionID string
ChannelID string
ClientConfig ibctesting.ClientConfig
ConnectionConfig *ibctesting.ConnectionConfig
ChannelConfig *ibctesting.ChannelConfig
}
// NewEndpoint constructs a new endpoint without the counterparty.
// CONTRACT: the counterparty endpoint must be set by the caller.
func NewEndpoint(
chain *TestChain, clientConfig ibctesting.ClientConfig,
connectionConfig *ibctesting.ConnectionConfig, channelConfig *ibctesting.ChannelConfig,
) *Endpoint {
return &Endpoint{
Chain: chain,
ClientConfig: clientConfig,
ConnectionConfig: connectionConfig,
ChannelConfig: channelConfig,
}
}
// NewDefaultEndpoint constructs a new endpoint using default values.
// CONTRACT: the counterparty endpoitn must be set by the caller.
func NewDefaultEndpoint(chain *TestChain) *Endpoint {
return &Endpoint{
Chain: chain,
ClientConfig: ibctesting.NewTendermintConfig(),
ConnectionConfig: ibctesting.NewConnectionConfig(),
ChannelConfig: ibctesting.NewChannelConfig(),
}
}
// QueryProof queries proof associated with this endpoint using the lastest client state
// height on the counterparty chain.
func (endpoint *Endpoint) QueryProof(key []byte) ([]byte, clienttypes.Height) {
// obtain the counterparty client representing the chain associated with the endpoint
clientState := endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID)
// query proof on the counterparty using the latest height of the IBC client
return endpoint.QueryProofAtHeight(key, clientState.GetLatestHeight().GetRevisionHeight())
}
// QueryProofAtHeight queries proof associated with this endpoint using the proof height
// providied
func (endpoint *Endpoint) QueryProofAtHeight(key []byte, height uint64) ([]byte, clienttypes.Height) {
// query proof on the counterparty using the latest height of the IBC client
return endpoint.Chain.QueryProofAtHeight(key, int64(height))
}
// CreateClient creates an IBC client on the endpoint. It will update the
// clientID for the endpoint if the message is successfully executed.
// NOTE: a solo machine client will be created with an empty diversifier.
func (endpoint *Endpoint) CreateClient() (err error) {
// ensure counterparty has committed state
endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain)
var (
clientState exported.ClientState
consensusState exported.ConsensusState
)
switch endpoint.ClientConfig.GetClientType() {
case exported.Tendermint:
tmConfig, ok := endpoint.ClientConfig.(*ibctesting.TendermintConfig)
require.True(endpoint.Chain.t, ok)
height := endpoint.Counterparty.Chain.LastHeader.GetHeight().(clienttypes.Height)
clientState = ibctmtypes.NewClientState(
endpoint.Counterparty.Chain.ChainID, tmConfig.TrustLevel, tmConfig.TrustingPeriod, tmConfig.UnbondingPeriod, tmConfig.MaxClockDrift,
height, commitmenttypes.GetSDKSpecs(), ibctesting.UpgradePath, tmConfig.AllowUpdateAfterExpiry, tmConfig.AllowUpdateAfterMisbehaviour,
)
consensusState = endpoint.Counterparty.Chain.LastHeader.ConsensusState()
case exported.Solomachine:
// TODO
// solo := NewSolomachine(chain.t, endpoint.Chain.Codec, clientID, "", 1)
// clientState = solo.ClientState()
// consensusState = solo.ConsensusState()
default:
err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType())
}
if err != nil {
return err
}
msg, err := clienttypes.NewMsgCreateClient(
clientState, consensusState, endpoint.Chain.SenderAccount.GetAddress().String(),
)
require.NoError(endpoint.Chain.t, err)
res, err := endpoint.Chain.SendMsgs(msg)
if err != nil {
return err
}
endpoint.ClientID, err = ibctesting.ParseClientIDFromEvents(res.GetEvents())
require.NoError(endpoint.Chain.t, err)
return nil
}
// UpdateClient updates the IBC client associated with the endpoint.
func (endpoint *Endpoint) UpdateClient() (err error) {
// ensure counterparty has committed state
endpoint.Chain.Coordinator.CommitBlock(endpoint.Counterparty.Chain)
var (
header exported.Header
)
switch endpoint.ClientConfig.GetClientType() {
case exported.Tendermint:
header, err = endpoint.Chain.ConstructUpdateTMClientHeader(endpoint.Counterparty.Chain, endpoint.ClientID)
default:
err = fmt.Errorf("client type %s is not supported", endpoint.ClientConfig.GetClientType())
}
if err != nil {
return err
}
msg, err := clienttypes.NewMsgUpdateClient(
endpoint.ClientID, header,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
require.NoError(endpoint.Chain.t, err)
return endpoint.Chain.sendMsgs(msg)
}
// ConnOpenInit will construct and execute a MsgConnectionOpenInit on the associated endpoint.
func (endpoint *Endpoint) ConnOpenInit() error {
msg := connectiontypes.NewMsgConnectionOpenInit(
endpoint.ClientID,
endpoint.Counterparty.ClientID,
endpoint.Counterparty.Chain.GetPrefix(), ibctesting.DefaultOpenInitVersion, endpoint.ConnectionConfig.DelayPeriod,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
res, err := endpoint.Chain.SendMsgs(msg)
if err != nil {
return err
}
endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents())
require.NoError(endpoint.Chain.t, err)
return nil
}
// ConnOpenTry will construct and execute a MsgConnectionOpenTry on the associated endpoint.
func (endpoint *Endpoint) ConnOpenTry() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
counterpartyClient, proofClient, proofConsensus, consensusHeight, proofInit, proofHeight := endpoint.QueryConnectionHandshakeProof()
msg := connectiontypes.NewMsgConnectionOpenTry(
"", endpoint.ClientID, // does not support handshake continuation
endpoint.Counterparty.ConnectionID, endpoint.Counterparty.ClientID,
counterpartyClient, endpoint.Counterparty.Chain.GetPrefix(), []*connectiontypes.Version{ibctesting.ConnectionVersion}, endpoint.ConnectionConfig.DelayPeriod,
proofInit, proofClient, proofConsensus,
proofHeight, consensusHeight,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
res, err := endpoint.Chain.SendMsgs(msg)
if err != nil {
return err
}
if endpoint.ConnectionID == "" {
endpoint.ConnectionID, err = ibctesting.ParseConnectionIDFromEvents(res.GetEvents())
require.NoError(endpoint.Chain.t, err)
}
return nil
}
// ConnOpenAck will construct and execute a MsgConnectionOpenAck on the associated endpoint.
func (endpoint *Endpoint) ConnOpenAck() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
counterpartyClient, proofClient, proofConsensus, consensusHeight, proofTry, proofHeight := endpoint.QueryConnectionHandshakeProof()
msg := connectiontypes.NewMsgConnectionOpenAck(
endpoint.ConnectionID, endpoint.Counterparty.ConnectionID, counterpartyClient, // testing doesn't use flexible selection
proofTry, proofClient, proofConsensus,
proofHeight, consensusHeight,
ibctesting.ConnectionVersion,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// ConnOpenConfirm will construct and execute a MsgConnectionOpenConfirm on the associated endpoint.
func (endpoint *Endpoint) ConnOpenConfirm() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID)
proof, height := endpoint.Counterparty.Chain.QueryProof(connectionKey)
msg := connectiontypes.NewMsgConnectionOpenConfirm(
endpoint.ConnectionID,
proof, height,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// QueryConnectionHandshakeProof returns all the proofs necessary to execute OpenTry or Open Ack of
// the connection handshakes. It returns the counterparty client state, proof of the counterparty
// client state, proof of the counterparty consensus state, the consensus state height, proof of
// the counterparty connection, and the proof height for all the proofs returned.
func (endpoint *Endpoint) QueryConnectionHandshakeProof() (
clientState exported.ClientState, proofClient,
proofConsensus []byte, consensusHeight clienttypes.Height,
proofConnection []byte, proofHeight clienttypes.Height,
) {
// obtain the client state on the counterparty chain
clientState = endpoint.Counterparty.Chain.GetClientState(endpoint.Counterparty.ClientID)
// query proof for the client state on the counterparty
clientKey := host.FullClientStateKey(endpoint.Counterparty.ClientID)
proofClient, proofHeight = endpoint.Counterparty.QueryProof(clientKey)
consensusHeight = clientState.GetLatestHeight().(clienttypes.Height)
// query proof for the consensus state on the counterparty
consensusKey := host.FullConsensusStateKey(endpoint.Counterparty.ClientID, consensusHeight)
proofConsensus, _ = endpoint.Counterparty.QueryProofAtHeight(consensusKey, proofHeight.GetRevisionHeight())
// query proof for the connection on the counterparty
connectionKey := host.ConnectionKey(endpoint.Counterparty.ConnectionID)
proofConnection, _ = endpoint.Counterparty.QueryProofAtHeight(connectionKey, proofHeight.GetRevisionHeight())
return
}
// ChanOpenInit will construct and execute a MsgChannelOpenInit on the associated endpoint.
func (endpoint *Endpoint) ChanOpenInit() error {
msg := channeltypes.NewMsgChannelOpenInit(
endpoint.ChannelConfig.PortID,
endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID},
endpoint.Counterparty.ChannelConfig.PortID,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
res, err := endpoint.Chain.SendMsgs(msg)
if err != nil {
return err
}
endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents())
require.NoError(endpoint.Chain.t, err)
return nil
}
// ChanOpenTry will construct and execute a MsgChannelOpenTry on the associated endpoint.
func (endpoint *Endpoint) ChanOpenTry() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID)
proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey)
msg := channeltypes.NewMsgChannelOpenTry(
endpoint.ChannelConfig.PortID, "", // does not support handshake continuation
endpoint.ChannelConfig.Version, endpoint.ChannelConfig.Order, []string{endpoint.ConnectionID},
endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version,
proof, height,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
res, err := endpoint.Chain.SendMsgs(msg)
if err != nil {
return err
}
if endpoint.ChannelID == "" {
endpoint.ChannelID, err = ibctesting.ParseChannelIDFromEvents(res.GetEvents())
require.NoError(endpoint.Chain.t, err)
}
return nil
}
// ChanOpenAck will construct and execute a MsgChannelOpenAck on the associated endpoint.
func (endpoint *Endpoint) ChanOpenAck() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID)
proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey)
msg := channeltypes.NewMsgChannelOpenAck(
endpoint.ChannelConfig.PortID, endpoint.ChannelID,
endpoint.Counterparty.ChannelID, endpoint.Counterparty.ChannelConfig.Version, // testing doesn't use flexible selection
proof, height,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// ChanOpenConfirm will construct and execute a MsgChannelOpenConfirm on the associated endpoint.
func (endpoint *Endpoint) ChanOpenConfirm() error {
if err := endpoint.UpdateClient(); err != nil {
return err
}
channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID)
proof, height := endpoint.Counterparty.Chain.QueryProof(channelKey)
msg := channeltypes.NewMsgChannelOpenConfirm(
endpoint.ChannelConfig.PortID, endpoint.ChannelID,
proof, height,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// ChanCloseInit will construct and execute a MsgChannelCloseInit on the associated endpoint.
//
// NOTE: does not work with ibc-transfer module
func (endpoint *Endpoint) ChanCloseInit() error {
msg := channeltypes.NewMsgChannelCloseInit(
endpoint.ChannelConfig.PortID, endpoint.ChannelID,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// ChanCloseConfirm will construct and execute a NewMsgChannelCloseConfirm on the associated endpoint.
func (endpoint *Endpoint) ChanCloseConfirm() error {
channelKey := host.ChannelKey(endpoint.Counterparty.ChannelConfig.PortID, endpoint.Counterparty.ChannelID)
proof, proofHeight := endpoint.Counterparty.QueryProof(channelKey)
msg := channeltypes.NewMsgChannelCloseConfirm(
endpoint.ChannelConfig.PortID, endpoint.ChannelID,
proof, proofHeight,
endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(msg)
}
// SendPacket sends a packet through the channel keeper using the associated endpoint
// The counterparty client is updated so proofs can be sent to the counterparty chain.
func (endpoint *Endpoint) SendPacket(packet exported.PacketI) error {
channelCap := endpoint.Chain.GetChannelCapability(packet.GetSourcePort(), packet.GetSourceChannel())
// no need to send message, acting as a module
err := endpoint.Chain.App.GetIBCKeeper().ChannelKeeper.SendPacket(endpoint.Chain.GetContext(), channelCap, packet)
if err != nil {
return err
}
// commit changes since no message was sent
endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain)
return endpoint.Counterparty.UpdateClient()
}
// RecvPacket receives a packet on the associated endpoint.
// The counterparty client is updated.
func (endpoint *Endpoint) RecvPacket(packet channeltypes.Packet) error {
// get proof of packet commitment on source
packetKey := host.PacketCommitmentKey(packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())
proof, proofHeight := endpoint.Counterparty.Chain.QueryProof(packetKey)
recvMsg := channeltypes.NewMsgRecvPacket(packet, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String())
// receive on counterparty and update source client
if err := endpoint.Chain.sendMsgs(recvMsg); err != nil {
return err
}
return endpoint.Counterparty.UpdateClient()
}
// WriteAcknowledgement writes an acknowledgement on the channel associated with the endpoint.
// The counterparty client is updated.
func (endpoint *Endpoint) WriteAcknowledgement(ack exported.Acknowledgement, packet exported.PacketI) error {
channelCap := endpoint.Chain.GetChannelCapability(packet.GetDestPort(), packet.GetDestChannel())
// no need to send message, acting as a handler
err := endpoint.Chain.App.GetIBCKeeper().ChannelKeeper.WriteAcknowledgement(endpoint.Chain.GetContext(), channelCap, packet, ack.Acknowledgement())
if err != nil {
return err
}
// commit changes since no message was sent
endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain)
return endpoint.Counterparty.UpdateClient()
}
// AcknowledgePacket sends a MsgAcknowledgement to the channel associated with the endpoint.
func (endpoint *Endpoint) AcknowledgePacket(packet channeltypes.Packet, ack []byte) error {
// get proof of acknowledgement on counterparty
packetKey := host.PacketAcknowledgementKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey)
ackMsg := channeltypes.NewMsgAcknowledgement(packet, ack, proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String())
return endpoint.Chain.sendMsgs(ackMsg)
}
// TimeoutPacket sends a MsgTimeout to the channel associated with the endpoint.
func (endpoint *Endpoint) TimeoutPacket(packet channeltypes.Packet) error {
// get proof for timeout based on channel order
var packetKey []byte
switch endpoint.ChannelConfig.Order {
case channeltypes.ORDERED:
packetKey = host.NextSequenceRecvKey(packet.GetDestPort(), packet.GetDestChannel())
case channeltypes.UNORDERED:
packetKey = host.PacketReceiptKey(packet.GetDestPort(), packet.GetDestChannel(), packet.GetSequence())
default:
return fmt.Errorf("unsupported order type %s", endpoint.ChannelConfig.Order)
}
proof, proofHeight := endpoint.Counterparty.QueryProof(packetKey)
nextSeqRecv, found := endpoint.Counterparty.Chain.App.GetIBCKeeper().ChannelKeeper.GetNextSequenceRecv(endpoint.Counterparty.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID)
require.True(endpoint.Chain.t, found)
timeoutMsg := channeltypes.NewMsgTimeout(
packet, nextSeqRecv,
proof, proofHeight, endpoint.Chain.SenderAccount.GetAddress().String(),
)
return endpoint.Chain.sendMsgs(timeoutMsg)
}
// SetChannelClosed sets a channel state to CLOSED.
func (endpoint *Endpoint) SetChannelClosed() error {
channel := endpoint.GetChannel()
channel.State = channeltypes.CLOSED
endpoint.Chain.App.GetIBCKeeper().ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel)
endpoint.Chain.Coordinator.CommitBlock(endpoint.Chain)
return endpoint.Counterparty.UpdateClient()
}
// GetClientState retrieves the Client State for this endpoint. The
// client state is expected to exist otherwise testing will fail.
func (endpoint *Endpoint) GetClientState() exported.ClientState {
return endpoint.Chain.GetClientState(endpoint.ClientID)
}
// SetClientState sets the client state for this endpoint.
func (endpoint *Endpoint) SetClientState(clientState exported.ClientState) {
endpoint.Chain.App.GetIBCKeeper().ClientKeeper.SetClientState(endpoint.Chain.GetContext(), endpoint.ClientID, clientState)
}
// GetConsensusState retrieves the Consensus State for this endpoint at the provided height.
// The consensus state is expected to exist otherwise testing will fail.
func (endpoint *Endpoint) GetConsensusState(height exported.Height) exported.ConsensusState {
consensusState, found := endpoint.Chain.GetConsensusState(endpoint.ClientID, height)
require.True(endpoint.Chain.t, found)
return consensusState
}
// SetConsensusState sets the consensus state for this endpoint.
func (endpoint *Endpoint) SetConsensusState(consensusState exported.ConsensusState, height exported.Height) {
endpoint.Chain.App.GetIBCKeeper().ClientKeeper.SetClientConsensusState(endpoint.Chain.GetContext(), endpoint.ClientID, height, consensusState)
}
// GetConnection retrieves an IBC Connection for the endpoint. The
// connection is expected to exist otherwise testing will fail.
func (endpoint *Endpoint) GetConnection() connectiontypes.ConnectionEnd {
connection, found := endpoint.Chain.App.GetIBCKeeper().ConnectionKeeper.GetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID)
require.True(endpoint.Chain.t, found)
return connection
}
// SetConnection sets the connection for this endpoint.
func (endpoint *Endpoint) SetConnection(connection connectiontypes.ConnectionEnd) {
endpoint.Chain.App.GetIBCKeeper().ConnectionKeeper.SetConnection(endpoint.Chain.GetContext(), endpoint.ConnectionID, connection)
}
// GetChannel retrieves an IBC Channel for the endpoint. The channel
// is expected to exist otherwise testing will fail.
func (endpoint *Endpoint) GetChannel() channeltypes.Channel {
channel, found := endpoint.Chain.App.GetIBCKeeper().ChannelKeeper.GetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID)
require.True(endpoint.Chain.t, found)
return channel
}
// SetChannel sets the channel for this endpoint.
func (endpoint *Endpoint) SetChannel(channel channeltypes.Channel) {
endpoint.Chain.App.GetIBCKeeper().ChannelKeeper.SetChannel(endpoint.Chain.GetContext(), endpoint.ChannelConfig.PortID, endpoint.ChannelID, channel)
}
// QueryClientStateProof performs and abci query for a client stat associated
// with this endpoint and returns the ClientState along with the proof.
func (endpoint *Endpoint) QueryClientStateProof() (exported.ClientState, []byte) {
// retrieve client state to provide proof for
clientState := endpoint.GetClientState()
clientKey := host.FullClientStateKey(endpoint.ClientID)
proofClient, _ := endpoint.QueryProof(clientKey)
return clientState, proofClient
}

View File

@ -0,0 +1,91 @@
package ibctesting
import (
"strconv"
"strings"
clienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
abci "github.com/tendermint/tendermint/abci/types"
)
func getSendPackets(evts []abci.Event) []channeltypes.Packet {
var res []channeltypes.Packet
for _, evt := range evts {
if evt.Type == "send_packet" {
packet := parsePacketFromEvent(evt)
res = append(res, packet)
}
}
return res
}
func getAckPackets(evts []abci.Event) []PacketAck {
var res []PacketAck
for _, evt := range evts {
if evt.Type == "write_acknowledgement" {
packet := parsePacketFromEvent(evt)
ack := PacketAck{
Packet: packet,
Ack: []byte(getField(evt, "packet_ack")),
}
res = append(res, ack)
}
}
return res
}
// Used for various debug statements above when needed... do not remove
// func showEvent(evt abci.Event) {
// fmt.Printf("evt.Type: %s\n", evt.Type)
// for _, attr := range evt.Attributes {
// fmt.Printf(" %s = %s\n", string(attr.Key), string(attr.Value))
// }
//}
func parsePacketFromEvent(evt abci.Event) channeltypes.Packet {
return channeltypes.Packet{
Sequence: getUintField(evt, "packet_sequence"),
SourcePort: getField(evt, "packet_src_port"),
SourceChannel: getField(evt, "packet_src_channel"),
DestinationPort: getField(evt, "packet_dst_port"),
DestinationChannel: getField(evt, "packet_dst_channel"),
Data: []byte(getField(evt, "packet_data")),
TimeoutHeight: parseTimeoutHeight(getField(evt, "packet_timeout_height")),
TimeoutTimestamp: getUintField(evt, "packet_timeout_timestamp"),
}
}
// return the value for the attribute with the given name
func getField(evt abci.Event, key string) string {
for _, attr := range evt.Attributes {
if string(attr.Key) == key {
return string(attr.Value)
}
}
return ""
}
func getUintField(evt abci.Event, key string) uint64 {
raw := getField(evt, key)
return toUint64(raw)
}
func toUint64(raw string) uint64 {
if raw == "" {
return 0
}
i, err := strconv.ParseUint(raw, 10, 64)
if err != nil {
panic(err)
}
return i
}
func parseTimeoutHeight(raw string) clienttypes.Height {
chunks := strings.Split(raw, "-")
return clienttypes.Height{
RevisionNumber: toUint64(chunks[0]),
RevisionHeight: toUint64(chunks[1]),
}
}

99
x/wasm/ibctesting/path.go Normal file
View File

@ -0,0 +1,99 @@
package ibctesting
import (
"bytes"
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
)
// Path contains two endpoints representing two chains connected over IBC
type Path struct {
EndpointA *Endpoint
EndpointB *Endpoint
}
// NewPath constructs an endpoint for each chain using the default values
// for the endpoints. Each endpoint is updated to have a pointer to the
// counterparty endpoint.
func NewPath(chainA, chainB *TestChain) *Path {
endpointA := NewDefaultEndpoint(chainA)
endpointB := NewDefaultEndpoint(chainB)
endpointA.Counterparty = endpointB
endpointB.Counterparty = endpointA
return &Path{
EndpointA: endpointA,
EndpointB: endpointB,
}
}
// SetChannelOrdered sets the channel order for both endpoints to ORDERED.
func (path *Path) SetChannelOrdered() {
path.EndpointA.ChannelConfig.Order = channeltypes.ORDERED
path.EndpointB.ChannelConfig.Order = channeltypes.ORDERED
}
// RelayPacket attempts to relay the packet first on EndpointA and then on EndpointB
// if EndpointA does not contain a packet commitment for that packet. An error is returned
// if a relay step fails or the packet commitment does not exist on either endpoint.
func (path *Path) RelayPacket(packet channeltypes.Packet, ack []byte) error {
pc := path.EndpointA.Chain.App.GetIBCKeeper().ChannelKeeper.GetPacketCommitment(path.EndpointA.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())
if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointA.Chain.App.AppCodec(), packet)) {
// packet found, relay from A to B
if err := path.EndpointB.UpdateClient(); err != nil {
return err
}
if err := path.EndpointB.RecvPacket(packet); err != nil {
return err
}
if err := path.EndpointA.AcknowledgePacket(packet, ack); err != nil {
return err
}
return nil
}
pc = path.EndpointB.Chain.App.GetIBCKeeper().ChannelKeeper.GetPacketCommitment(path.EndpointB.Chain.GetContext(), packet.GetSourcePort(), packet.GetSourceChannel(), packet.GetSequence())
if bytes.Equal(pc, channeltypes.CommitPacket(path.EndpointB.Chain.App.AppCodec(), packet)) {
// packet found, relay B to A
if err := path.EndpointA.UpdateClient(); err != nil {
return err
}
if err := path.EndpointA.RecvPacket(packet); err != nil {
return err
}
if err := path.EndpointB.AcknowledgePacket(packet, ack); err != nil {
return err
}
return nil
}
return fmt.Errorf("packet commitment does not exist on either endpoint for provided packet")
}
// SendMsg delivers the provided messages to the chain. The counterparty
// client is updated with the new source consensus state.
func (path *Path) SendMsg(msgs ...sdk.Msg) error {
if err := path.EndpointA.Chain.sendMsgs(msgs...); err != nil {
return err
}
if err := path.EndpointA.UpdateClient(); err != nil {
return err
}
return path.EndpointB.UpdateClient()
}
func (path *Path) Invert() *Path {
return &Path{
EndpointA: path.EndpointB,
EndpointB: path.EndpointA,
}
}

View File

@ -8,13 +8,16 @@ import (
"io/ioutil"
"strings"
wasmd "github.com/CosmWasm/wasmd/app"
ibctesting "github.com/cosmos/ibc-go/v2/testing"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/golang/protobuf/proto" //nolint
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/rand"
wasmd "github.com/CosmWasm/wasmd/app"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
@ -71,7 +74,7 @@ func (chain *TestChain) InstantiateContract(codeID uint64, initMsg []byte) sdk.A
CodeID: codeID,
Label: "ibc-test",
Msg: initMsg,
Funds: sdk.Coins{TestCoin},
Funds: sdk.Coins{ibctesting.TestCoin},
}
r, err := chain.SendMsgs(instantiateMsg)
@ -132,10 +135,8 @@ func (chain *TestChain) parseSDKResultData(r *sdk.Result) sdk.TxMsgData {
// ContractInfo is a helper function to returns the ContractInfo for the given contract address
func (chain *TestChain) ContractInfo(contractAddr sdk.AccAddress) *types.ContractInfo {
return chain.TestSupport().WasmKeeper().GetContractInfo(chain.GetContext(), contractAddr)
}
// TestSupport provides access to package private keepers.
func (chain *TestChain) TestSupport() *wasmd.TestSupport {
return wasmd.NewTestSupport(chain.t, chain.App)
type testSupporter interface {
TestSupport() *wasmd.TestSupport
}
return chain.App.(testSupporter).TestSupport().WasmKeeper().GetContractInfo(chain.GetContext(), contractAddr)
}

View File

@ -1,8 +1,6 @@
package keeper
import (
"fmt"
wasmvm "github.com/CosmWasm/wasmvm"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
sdk "github.com/cosmos/cosmos-sdk/types"
@ -28,8 +26,8 @@ var (
)
func humanAddress(canon []byte) (string, uint64, error) {
if len(canon) != sdk.AddrLen {
return "", costHumanize, fmt.Errorf("expected %d byte address", sdk.AddrLen)
if err := sdk.VerifyAddressFormat(canon); err != nil {
return "", costHumanize, err
}
return sdk.AccAddress(canon).String(), costHumanize, nil
}

View File

@ -474,7 +474,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
],
"contracts": [
{
"contract_address": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6",
"contract_address": "cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr",
"contract_info": {
"code_id": "1",
"creator": "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x",
@ -484,8 +484,8 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
}
],
"sequences": [
{"id_key": %q, "value": "2"},
{"id_key": %q, "value": "2"}
{"id_key": "BGxhc3RDb2RlSWQ=", "value": "2"},
{"id_key": "BGxhc3RDb250cmFjdElk", "value": "3"}
]
}`
keeper, ctx, _ := setupKeeper(t)
@ -496,9 +496,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
wasmCodeHash := sha256.Sum256(wasmCode)
enc64 := base64.StdEncoding.EncodeToString
genesisStr := fmt.Sprintf(genesisTemplate, enc64(wasmCodeHash[:]), enc64(wasmCode),
enc64(append([]byte{0x04}, []byte("lastCodeId")...)),
enc64(append([]byte{0x04}, []byte("lastContractId")...)))
genesisStr := fmt.Sprintf(genesisTemplate, enc64(wasmCodeHash[:]), enc64(wasmCode))
var importState wasmTypes.GenesisState
err = keeper.cdc.UnmarshalJSON([]byte(genesisStr), &importState)
@ -531,7 +529,7 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
assert.Equal(t, expCodeInfo, *gotCodeInfo)
// verify contract
contractAddr, _ := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhuc53mp6")
contractAddr, _ := sdk.AccAddressFromBech32("cosmos14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmalr")
gotContractInfo := keeper.GetContractInfo(ctx, contractAddr)
require.NotNil(t, gotContractInfo)
contractCreatorAddr := "cosmos13x849jzd03vne42ynpj25hn8npjecxqrjghd8x"
@ -553,15 +551,17 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) {
},
}
assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr))
assert.Equal(t, uint64(2), keeper.PeekAutoIncrementID(ctx, types.KeyLastCodeID))
assert.Equal(t, uint64(3), keeper.PeekAutoIncrementID(ctx, types.KeyLastInstanceID))
}
func TestSupportedGenMsgTypes(t *testing.T) {
wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm")
require.NoError(t, err)
var (
myAddress sdk.AccAddress = bytes.Repeat([]byte{1}, sdk.AddrLen)
verifierAddress sdk.AccAddress = bytes.Repeat([]byte{2}, sdk.AddrLen)
beneficiaryAddress sdk.AccAddress = bytes.Repeat([]byte{3}, sdk.AddrLen)
myAddress sdk.AccAddress = bytes.Repeat([]byte{1}, types.ContractAddrLen)
verifierAddress sdk.AccAddress = bytes.Repeat([]byte{2}, types.ContractAddrLen)
beneficiaryAddress sdk.AccAddress = bytes.Repeat([]byte{3}, types.ContractAddrLen)
)
const denom = "stake"
importState := types.GenesisState{
@ -604,7 +604,8 @@ func TestSupportedGenMsgTypes(t *testing.T) {
ctx, keepers := CreateDefaultTestInput(t)
keeper := keepers.WasmKeeper
ctx = ctx.WithBlockHeight(0).WithGasMeter(sdk.NewInfiniteGasMeter())
fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, myAddress, sdk.NewCoins(sdk.NewCoin(denom, sdk.NewInt(100))))
keepers.Faucet.Fund(ctx, myAddress, sdk.NewCoin(denom, sdk.NewInt(100)))
// when
_, err = InitGenesis(ctx, keeper, importState, &StakingKeeperMock{}, TestHandler(keepers.ContractKeeper))
require.NoError(t, err)
@ -660,7 +661,7 @@ func setupKeeper(t *testing.T) (*Keeper, sdk.Context, []sdk.StoreKey) {
wasmConfig := wasmTypes.DefaultWasmConfig()
pk := paramskeeper.NewKeeper(encodingConfig.Marshaler, encodingConfig.Amino, keyParams, tkeyParams)
srcKeeper := NewKeeper(encodingConfig.Marshaler, keyWasm, pk.Subspace(wasmTypes.DefaultParamspace), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, nil, nil, nil, nil, nil, tempDir, wasmConfig, SupportedFeatures)
srcKeeper := NewKeeper(encodingConfig.Marshaler, keyWasm, pk.Subspace(wasmTypes.ModuleName), authkeeper.AccountKeeper{}, nil, stakingkeeper.Keeper{}, distributionkeeper.Keeper{}, nil, nil, nil, nil, nil, nil, tempDir, wasmConfig, SupportedFeatures)
return &srcKeeper, ctx, []sdk.StoreKey{keyWasm, keyParams}
}

View File

@ -5,11 +5,12 @@ import (
"fmt"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"
"github.com/cosmos/cosmos-sdk/baseapp"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
host "github.com/cosmos/cosmos-sdk/x/ibc/core/24-host"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
"github.com/CosmWasm/wasmd/x/wasm/types"
)
@ -20,14 +21,19 @@ type msgEncoder interface {
Encode(ctx sdk.Context, contractAddr sdk.AccAddress, contractIBCPortID string, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error)
}
// MessageRouter ADR 031 request type routing
type MessageRouter interface {
Handler(msg sdk.Msg) baseapp.MsgServiceHandler
}
// SDKMessageHandler can handles messages that can be encoded into sdk.Message types and routed.
type SDKMessageHandler struct {
router sdk.Router
router MessageRouter
encoders msgEncoder
}
func NewDefaultMessageHandler(
router sdk.Router,
router MessageRouter,
channelKeeper types.ChannelKeeper,
capabilityKeeper types.CapabilityKeeper,
bankKeeper types.Burner,
@ -46,7 +52,7 @@ func NewDefaultMessageHandler(
)
}
func NewSDKMessageHandler(router sdk.Router, encoders msgEncoder) SDKMessageHandler {
func NewSDKMessageHandler(router MessageRouter, encoders msgEncoder) SDKMessageHandler {
return SDKMessageHandler{
router: router,
encoders: encoders,
@ -87,15 +93,17 @@ func (h SDKMessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Ad
}
// find the handler and execute it
handler := h.router.Route(ctx, msg.Route())
if handler == nil {
return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, msg.Route())
if handler := h.router.Handler(msg); handler != nil {
// ADR 031 request type routing
msgResult, err := handler(ctx, msg)
return msgResult, err
}
res, err := handler(ctx, msg)
if err != nil {
return nil, err
}
return res, nil
// legacy sdk.Msg routing
// Assuming that the app developer has migrated all their Msgs to
// proto messages and has registered all `Msg services`, then this
// path should never be called, because all those Msgs should be
// registered within the `msgServiceRouter` already.
return nil, sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "can't route message %+v", msg)
}
// MessageHandlerChain defines a chain of handlers that are called one by one until it can be handled.

View File

@ -11,10 +11,10 @@ import (
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
ibcclienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
ibctransfertypes "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types"
ibcclienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
"github.com/CosmWasm/wasmd/x/wasm/types"
)

View File

@ -5,9 +5,9 @@ import (
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
govtypes "github.com/cosmos/cosmos-sdk/x/gov/types"
ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types"
clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/core/02-client/types"
channeltypes "github.com/cosmos/cosmos-sdk/x/ibc/core/04-channel/types"
ibctransfertypes "github.com/cosmos/ibc-go/v2/modules/apps/transfer/types"
clienttypes "github.com/cosmos/ibc-go/v2/modules/core/02-client/types"
channeltypes "github.com/cosmos/ibc-go/v2/modules/core/04-channel/types"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/assert"
@ -29,9 +29,9 @@ func TestEncoding(t *testing.T) {
addr3 = RandomAccountAddress(t)
invalidAddr = "xrnd1d02kd90n38qvr3qb9qof83fn2d2"
)
valAddr := make(sdk.ValAddress, sdk.AddrLen)
valAddr := make(sdk.ValAddress, types.SDKAddrLen)
valAddr[0] = 12
valAddr2 := make(sdk.ValAddress, sdk.AddrLen)
valAddr2 := make(sdk.ValAddress, types.SDKAddrLen)
valAddr2[1] = 123
jsonMsg := types.RawContractMessage(`{"foo": 123}`)

Some files were not shown because too many files have changed in this diff Show More