diff --git a/Makefile b/Makefile index 22d75bc567..93d3c6a049 100644 --- a/Makefile +++ b/Makefile @@ -40,16 +40,16 @@ endif build_tags += $(BUILD_TAGS) build_tags := $(strip $(build_tags)) -empty := -space := $(empty) $(empty) +whitespace := +empty = $(whitespace) $(whitespace) comma := , -build_tags_comma_sep := $(subst $(space),$(comma),$(build_tags)) +build_tags_comma_sep := $(subst $(empty),$(comma),$(build_tags)) # process linker flags ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=wasm \ - -X github.com/cosmos/cosmos-sdk/version.ServerName=wasmd \ - -X github.com/cosmos/cosmos-sdk/version.ClientName=wasmcli \ + -X github.com/cosmos/cosmos-sdk/version.AppName=wasmd \ + -X github.com/CosmWasm/wasmd/cmd/wasmcli/version.ClientName=wasmcli \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ -X "github.com/cosmos/cosmos-sdk/version.BuildTags=$(build_tags_comma_sep)" @@ -61,8 +61,8 @@ ldflags += $(LDFLAGS) ldflags := $(strip $(ldflags)) coral_ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=coral \ - -X github.com/cosmos/cosmos-sdk/version.ServerName=corald \ - -X github.com/cosmos/cosmos-sdk/version.ClientName=coral \ + -X github.com/cosmos/cosmos-sdk/version.AppName=corald \ + -X github.com/CosmWasm/wasmd/cmd/wasmcli/version.ClientName=coral \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ -X github.com/CosmWasm/wasmd/app.CLIDir=.coral \ @@ -76,8 +76,8 @@ coral_ldflags += $(LDFLAGS) coral_ldflags := $(strip $(coral_ldflags)) flex_ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=gaiaflex \ - -X github.com/cosmos/cosmos-sdk/version.ServerName=gaiaflexd \ - -X github.com/cosmos/cosmos-sdk/version.ClientName=gaiaflex \ + -X github.com/cosmos/cosmos-sdk/version.AppName=gaiaflexd \ + -X github.com/CosmWasm/wasmd/cmd/wasmcli/version.ClientName=gaiaflex \ -X github.com/cosmos/cosmos-sdk/version.Version=$(VERSION) \ -X github.com/cosmos/cosmos-sdk/version.Commit=$(COMMIT) \ -X github.com/CosmWasm/wasmd/app.ProposalsEnabled=true \ @@ -89,9 +89,9 @@ flex_ldflags = -X github.com/cosmos/cosmos-sdk/version.Name=gaiaflex \ flex_ldflags += $(LDFLAGS) flex_ldflags := $(strip $(flex_ldflags)) -BUILD_FLAGS := -tags $(build_tags_comma_sep) -ldflags '$(ldflags)' -trimpath -CORAL_BUILD_FLAGS := -tags $(build_tags_comma_sep) -ldflags '$(coral_ldflags)' -trimpath -FLEX_BUILD_FLAGS := -tags $(build_tags_comma_sep) -ldflags '$(flex_ldflags)' -trimpath +BUILD_FLAGS := -tags "$(build_tags_comma_sep)" -ldflags '$(ldflags)' -trimpath +CORAL_BUILD_FLAGS := -tags "$(build_tags_comma_sep)" -ldflags '$(coral_ldflags)' -trimpath +FLEX_BUILD_FLAGS := -tags "$(build_tags_comma_sep)" -ldflags '$(flex_ldflags)' -trimpath all: install lint test @@ -162,7 +162,7 @@ distclean: clean ### Testing -test: test-unit test-build +test: test-unit test-all: check test-race test-cover test-unit: @@ -174,16 +174,39 @@ test-race: test-cover: @go test -mod=readonly -timeout 30m -race -coverprofile=coverage.txt -covermode=atomic -tags='ledger test_ledger_mock' ./... -test-build: build - @go test -mod=readonly -p 4 `go list ./cli_test/...` -tags=cli_test -v + +benchmark: + @go test -mod=readonly -bench=. ./... + + +############################################################################### +### Linting ### +############################################################################### + +lint: + golangci-lint run + find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" | xargs gofmt -d -s format: find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs gofmt -w -s find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs misspell -w find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/lcd/statik/statik.go" | xargs goimports -w -local github.com/CosmWasm/wasmd -benchmark: - @go test -mod=readonly -bench=. ./... + +############################################################################### +### Protobuf ### +############################################################################### + +proto-all: proto-gen proto-lint proto-check-breaking + +proto-gen: + @./scripts/protocgen.sh + +proto-lint: + @buf check lint --error-format=json + +proto-check-breaking: + @buf check breaking --against-input '.git#branch=master' .PHONY: all build-linux install install-debug \ diff --git a/README.md b/README.md index b0dc3ebcc6..cbd0a1df08 100644 --- a/README.md +++ b/README.md @@ -2,10 +2,10 @@ [![CircleCI](https://circleci.com/gh/cosmwasm/wasmd/tree/master.svg?style=shield)](https://circleci.com/gh/cosmwasm/wasmd/tree/master) [![codecov](https://codecov.io/gh/cosmwasm/wasmd/branch/master/graph/badge.svg)](https://codecov.io/gh/cosmwasm/wasmd) -[![Go Report Card](https://goreportcard.com/badge/github.com/cosmwasm/wasmd)](https://goreportcard.com/report/github.com/cosmwasm/wasmd) -[![license](https://img.shields.io/github/license/cosmwasm/wasmd.svg)](https://github.com/cosmwasm/wasmd/blob/master/LICENSE) -[![LoC](https://tokei.rs/b1/github/cosmwasm/wasmd)](https://github.com/cosmwasm/wasmd) - +[![Go Report Card](https://goreportcard.com/badge/github.com/CosmWasm/wasmd)](https://goreportcard.com/report/github.com/CosmWasm/wasmd) +[![license](https://img.shields.io/github/license/cosmwasm/wasmd.svg)](https://github.com/CosmWasm/wasmd/blob/master/LICENSE) +[![LoC](https://tokei.rs/b1/github/cosmwasm/wasmd)](https://github.com/CosmWasm/wasmd) + This repository hosts `Wasmd`, the first implementation of a cosmos zone with wasm smart contracts enabled. @@ -46,6 +46,7 @@ Thank you to all projects who have run this code in your testnets and given feedback to improve stability. ## Encoding +The used cosmos-sdk version is in transition migrating from amino encoding to protobuf for state. So are we now. We use standard cosmos-sdk encoding (amino) for all sdk Messages. However, the message body sent to all contracts, as well as the internal state is encoded using JSON. Cosmwasm allows arbitrary bytes with the contract itself @@ -60,12 +61,32 @@ your use case. make install make test ``` -if you are using a linux without X or headless linux, look at [this article](https://ahelpme.com/linux/dbusexception-could-not-get-owner-of-name-org-freedesktop-secrets-no-such-name) or [#31](https://github.com/cosmwasm/wasmd/issues/31#issuecomment-577058321). +if you are using a linux without X or headless linux, look at [this article](https://ahelpme.com/linux/dbusexception-could-not-get-owner-of-name-org-freedesktop-secrets-no-such-name) or [#31](https://github.com/CosmWasm/wasmd/issues/31#issuecomment-577058321). To set up a single node testnet, [look at the deployment documentation](./docs/deploy-testnet.md). If you want to deploy a whole cluster, [look at the network scripts](./networks/README.md). +## Protobuf + +1. Install [protoc](https://github.com/protocolbuffers/protobuf#protocol-compiler-installation) + +2. Install [cosmos-extension](https://github.com/regen-network/cosmos-proto/) for [gogo-protobuf](https://github.com/gogo/protobuf) +```sh +go install github.com/regen-network/cosmos-proto/protoc-gen-gocosmos +``` +3. Install [grpc gateway extension](github.com/grpc-ecosystem/grpc-gateway) +```go +go install \ upgrade_stargate_rebased 3a8aa77 ✗ + github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \ + github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger \ + github.com/golang/protobuf/protoc-gen-go +``` +3. Run generator +```sh + make proto-gen +``` + ## Dockerized We provide a docker image to help with test setups. There are two modes to use it diff --git a/app/app.go b/app/app.go index 41978097a5..e9706455b8 100644 --- a/app/app.go +++ b/app/app.go @@ -2,40 +2,91 @@ package app import ( "io" + "net/http" "os" "path/filepath" "strings" + "github.com/gorilla/mux" + "github.com/rakyll/statik/fs" + "github.com/spf13/viper" + 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/CosmWasm/wasmd/x/wasm" wasmclient "github.com/CosmWasm/wasmd/x/wasm/client" - bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/server/api" + "github.com/cosmos/cosmos-sdk/server/config" "github.com/cosmos/cosmos-sdk/simapp" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/version" "github.com/cosmos/cosmos-sdk/x/auth" - authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting" + "github.com/cosmos/cosmos-sdk/x/auth/ante" + authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + authsims "github.com/cosmos/cosmos-sdk/x/auth/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/auth/vesting" "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" + "github.com/cosmos/cosmos-sdk/x/capability" + capabilitykeeper "github.com/cosmos/cosmos-sdk/x/capability/keeper" + capabilitytypes "github.com/cosmos/cosmos-sdk/x/capability/types" "github.com/cosmos/cosmos-sdk/x/crisis" + crisiskeeper "github.com/cosmos/cosmos-sdk/x/crisis/keeper" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" distr "github.com/cosmos/cosmos-sdk/x/distribution" + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" + distrkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "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/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" "github.com/cosmos/cosmos-sdk/x/params" paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/cosmos/cosmos-sdk/x/slashing" + slashingkeeper "github.com/cosmos/cosmos-sdk/x/slashing/keeper" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/cosmos/cosmos-sdk/x/upgrade" upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - tmos "github.com/tendermint/tendermint/libs/os" - dbm "github.com/tendermint/tm-db" + upgradekeeper "github.com/cosmos/cosmos-sdk/x/upgrade/keeper" + upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types" + + // unnamed import of statik for swagger UI support + _ "github.com/cosmos/cosmos-sdk/client/docs/statik" ) const appName = "WasmApp" @@ -96,82 +147,85 @@ var ( ) var ( - // ModuleBasics The module BasicManager is in charge of setting up basic, + // ModuleBasics defines the module BasicManager is in charge of setting up basic, // non-dependant module elements, such as codec registration // and genesis verification. ModuleBasics = module.NewBasicManager( - genutil.AppModuleBasic{}, auth.AppModuleBasic{}, + genutil.AppModuleBasic{}, bank.AppModuleBasic{}, + capability.AppModuleBasic{}, staking.AppModuleBasic{}, mint.AppModuleBasic{}, distr.AppModuleBasic{}, - gov.NewAppModuleBasic(append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distr.ProposalHandler, upgradeclient.ProposalHandler)...), + gov.NewAppModuleBasic( + append(wasmclient.ProposalHandlers, paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler)..., + ), params.AppModuleBasic{}, wasm.AppModuleBasic{}, crisis.AppModuleBasic{}, slashing.AppModuleBasic{}, - supply.AppModuleBasic{}, + ibc.AppModuleBasic{}, upgrade.AppModuleBasic{}, evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, + vesting.AppModuleBasic{}, ) // module account permissions maccPerms = map[string][]string{ - auth.FeeCollectorName: nil, - distr.ModuleName: nil, - mint.ModuleName: {supply.Minter}, - staking.BondedPoolName: {supply.Burner, supply.Staking}, - staking.NotBondedPoolName: {supply.Burner, supply.Staking}, - gov.ModuleName: {supply.Burner}, + authtypes.FeeCollectorName: nil, + distrtypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, } -) - -// MakeCodec creates the application codec. The codec is sealed before it is -// returned. -func MakeCodec() *codec.Codec { - var cdc = codec.New() - ModuleBasics.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - codec.RegisterEvidences(cdc) - authvesting.RegisterCodec(cdc) - - return cdc.Seal() -} + // module accounts that are allowed to receive tokens + allowedReceivingModAcc = map[string]bool{ + distrtypes.ModuleName: true, + } +) // Verify app interface at compile time var _ simapp.App = (*WasmApp)(nil) // WasmApp extended ABCI application type WasmApp struct { - *bam.BaseApp - cdc *codec.Codec + *baseapp.BaseApp + legacyAmino *codec.LegacyAmino + appCodec codec.Marshaler + interfaceRegistry types.InterfaceRegistry invCheckPeriod uint // keys to access the substores - keys map[string]*sdk.KVStoreKey - tKeys map[string]*sdk.TransientStoreKey - - // subspaces - subspaces map[string]params.Subspace + keys map[string]*sdk.KVStoreKey + tkeys map[string]*sdk.TransientStoreKey + memKeys map[string]*sdk.MemoryStoreKey // keepers - accountKeeper auth.AccountKeeper - bankKeeper bank.Keeper - supplyKeeper supply.Keeper - stakingKeeper staking.Keeper - slashingKeeper slashing.Keeper - mintKeeper mint.Keeper - distrKeeper distr.Keeper - govKeeper gov.Keeper - crisisKeeper crisis.Keeper - paramsKeeper params.Keeper - evidenceKeeper *evidence.Keeper - upgradeKeeper upgrade.Keeper - wasmKeeper wasm.Keeper + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper + capabilityKeeper *capabilitykeeper.Keeper + stakingKeeper stakingkeeper.Keeper + slashingKeeper slashingkeeper.Keeper + mintKeeper mintkeeper.Keeper + distrKeeper distrkeeper.Keeper + govKeeper govkeeper.Keeper + crisisKeeper crisiskeeper.Keeper + upgradeKeeper upgradekeeper.Keeper + paramsKeeper paramskeeper.Keeper + 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 + wasmKeeper wasm.Keeper + + // make scoped keepers public for test purposes + ScopedIBCKeeper capabilitykeeper.ScopedKeeper + ScopedTransferKeeper capabilitykeeper.ScopedKeeper // the module manager mm *module.Manager @@ -188,106 +242,117 @@ type WasmWrapper struct { // NewWasmApp returns a reference to an initialized WasmApp. func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, - invCheckPeriod uint, enabledProposals []wasm.ProposalType, skipUpgradeHeights map[int64]bool, - baseAppOptions ...func(*bam.BaseApp)) *WasmApp { + skipUpgradeHeights map[int64]bool, homePath string, invCheckPeriod uint, enabledProposals []wasm.ProposalType, + baseAppOptions ...func(*baseapp.BaseApp)) *WasmApp { - cdc := MakeCodec() + encodingConfig := MakeEncodingConfig() + appCodec, legacyAmino := encodingConfig.Marshaler, encodingConfig.Amino + interfaceRegistry := encodingConfig.InterfaceRegistry - debug := viper.GetBool(cli.TraceFlag) - baseAppOptions = append(baseAppOptions, bam.SetTrace(debug)) - - bApp := bam.NewBaseApp(appName, logger, db, auth.DefaultTxDecoder(cdc), baseAppOptions...) + bApp := baseapp.NewBaseApp(appName, logger, db, encodingConfig.TxConfig.TxDecoder(), baseAppOptions...) bApp.SetCommitMultiStoreTracer(traceStore) bApp.SetAppVersion(version.Version) + bApp.SetInterfaceRegistry(interfaceRegistry) + bApp.GRPCQueryRouter().RegisterSimulateService(bApp.Simulate, interfaceRegistry) keys := sdk.NewKVStoreKeys( - bam.MainStoreKey, auth.StoreKey, staking.StoreKey, - supply.StoreKey, mint.StoreKey, distr.StoreKey, slashing.StoreKey, - gov.StoreKey, params.StoreKey, evidence.StoreKey, upgrade.StoreKey, + authtypes.StoreKey, banktypes.StoreKey, stakingtypes.StoreKey, + minttypes.StoreKey, distrtypes.StoreKey, slashingtypes.StoreKey, + govtypes.StoreKey, paramstypes.StoreKey, ibchost.StoreKey, upgradetypes.StoreKey, + evidencetypes.StoreKey, ibctransfertypes.StoreKey, capabilitytypes.StoreKey, wasm.StoreKey, ) - tKeys := sdk.NewTransientStoreKeys(staking.TStoreKey, params.TStoreKey) + tkeys := sdk.NewTransientStoreKeys(paramstypes.TStoreKey) + memKeys := sdk.NewMemoryStoreKeys(capabilitytypes.MemStoreKey) app := &WasmApp{ - BaseApp: bApp, - cdc: cdc, - invCheckPeriod: invCheckPeriod, - keys: keys, - tKeys: tKeys, - subspaces: make(map[string]params.Subspace), + BaseApp: bApp, + legacyAmino: legacyAmino, + appCodec: appCodec, + interfaceRegistry: interfaceRegistry, + invCheckPeriod: invCheckPeriod, + keys: keys, + tkeys: tkeys, + memKeys: memKeys, } - // init params keeper and subspaces - app.paramsKeeper = params.NewKeeper(app.cdc, keys[params.StoreKey], tKeys[params.TStoreKey]) - app.subspaces[auth.ModuleName] = app.paramsKeeper.Subspace(auth.DefaultParamspace) - app.subspaces[bank.ModuleName] = app.paramsKeeper.Subspace(bank.DefaultParamspace) - app.subspaces[staking.ModuleName] = app.paramsKeeper.Subspace(staking.DefaultParamspace) - app.subspaces[mint.ModuleName] = app.paramsKeeper.Subspace(mint.DefaultParamspace) - app.subspaces[distr.ModuleName] = app.paramsKeeper.Subspace(distr.DefaultParamspace) - app.subspaces[slashing.ModuleName] = app.paramsKeeper.Subspace(slashing.DefaultParamspace) - app.subspaces[gov.ModuleName] = app.paramsKeeper.Subspace(gov.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()) - app.subspaces[crisis.ModuleName] = app.paramsKeeper.Subspace(crisis.DefaultParamspace) - app.subspaces[evidence.ModuleName] = app.paramsKeeper.Subspace(evidence.DefaultParamspace) - app.subspaces[wasm.ModuleName] = app.paramsKeeper.Subspace(wasm.DefaultParamspace) + 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]) + scopedIBCKeeper := app.capabilityKeeper.ScopeToModule(ibchost.ModuleName) + scopedTransferKeeper := app.capabilityKeeper.ScopeToModule(ibctransfertypes.ModuleName) // add keepers - app.accountKeeper = auth.NewAccountKeeper( - app.cdc, keys[auth.StoreKey], app.subspaces[auth.ModuleName], auth.ProtoBaseAccount, - ) - app.bankKeeper = bank.NewBaseKeeper( - app.accountKeeper, app.subspaces[bank.ModuleName], app.ModuleAccountAddrs(), + app.accountKeeper = authkeeper.NewAccountKeeper( + appCodec, keys[authtypes.StoreKey], app.getSubspace(authtypes.ModuleName), authtypes.ProtoBaseAccount, maccPerms, ) - app.supplyKeeper = supply.NewKeeper( - app.cdc, keys[supply.StoreKey], app.accountKeeper, app.bankKeeper, maccPerms, + app.bankKeeper = bankkeeper.NewBaseKeeper( + appCodec, keys[banktypes.StoreKey], app.accountKeeper, app.getSubspace(banktypes.ModuleName), app.BlockedAddrs(), ) - stakingKeeper := staking.NewKeeper( - app.cdc, keys[staking.StoreKey], app.supplyKeeper, app.subspaces[staking.ModuleName], + stakingKeeper := stakingkeeper.NewKeeper( + appCodec, keys[stakingtypes.StoreKey], app.accountKeeper, app.bankKeeper, app.getSubspace(stakingtypes.ModuleName), ) - app.mintKeeper = mint.NewKeeper( - app.cdc, keys[mint.StoreKey], app.subspaces[mint.ModuleName], &stakingKeeper, - app.supplyKeeper, auth.FeeCollectorName, + app.mintKeeper = mintkeeper.NewKeeper( + appCodec, keys[minttypes.StoreKey], app.getSubspace(minttypes.ModuleName), &stakingKeeper, + app.accountKeeper, app.bankKeeper, authtypes.FeeCollectorName, ) - app.distrKeeper = distr.NewKeeper( - app.cdc, keys[distr.StoreKey], app.subspaces[distr.ModuleName], &stakingKeeper, - app.supplyKeeper, auth.FeeCollectorName, app.ModuleAccountAddrs(), + app.distrKeeper = distrkeeper.NewKeeper( + appCodec, keys[distrtypes.StoreKey], app.getSubspace(distrtypes.ModuleName), app.accountKeeper, app.bankKeeper, + &stakingKeeper, authtypes.FeeCollectorName, app.ModuleAccountAddrs(), ) - app.slashingKeeper = slashing.NewKeeper( - app.cdc, keys[slashing.StoreKey], &stakingKeeper, app.subspaces[slashing.ModuleName], + app.slashingKeeper = slashingkeeper.NewKeeper( + appCodec, keys[slashingtypes.StoreKey], &stakingKeeper, app.getSubspace(slashingtypes.ModuleName), ) - app.crisisKeeper = crisis.NewKeeper( - app.subspaces[crisis.ModuleName], invCheckPeriod, app.supplyKeeper, auth.FeeCollectorName, + app.crisisKeeper = crisiskeeper.NewKeeper( + app.getSubspace(crisistypes.ModuleName), invCheckPeriod, app.bankKeeper, authtypes.FeeCollectorName, ) - app.upgradeKeeper = upgrade.NewKeeper(skipUpgradeHeights, keys[upgrade.StoreKey], app.cdc) + app.upgradeKeeper = upgradekeeper.NewKeeper(skipUpgradeHeights, keys[upgradetypes.StoreKey], appCodec, homePath) - // create evidence keeper with evidence router - evidenceKeeper := evidence.NewKeeper( - app.cdc, keys[evidence.StoreKey], app.subspaces[evidence.ModuleName], &stakingKeeper, app.slashingKeeper, + // register the staking hooks + // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks + app.stakingKeeper = *stakingKeeper.SetHooks( + stakingtypes.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), ) - evidenceRouter := evidence.NewRouter() - - // TODO: register evidence routes - evidenceKeeper.SetRouter(evidenceRouter) - app.evidenceKeeper = evidenceKeeper + // Create IBC Keeper + app.ibcKeeper = ibckeeper.NewKeeper( + appCodec, keys[ibchost.StoreKey], app.stakingKeeper, scopedIBCKeeper, + ) // register the proposal types - govRouter := gov.NewRouter() - govRouter.AddRoute(gov.RouterKey, gov.ProposalHandler). - AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(app.paramsKeeper)). - AddRoute(distr.RouterKey, distr.NewCommunityPoolSpendProposalHandler(app.distrKeeper)). - AddRoute(upgrade.RouterKey, upgrade.NewSoftwareUpgradeProposalHandler(app.upgradeKeeper)) + govRouter := govtypes.NewRouter() + 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)) + + // 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, + ) + transferModule := transfer.NewAppModule(app.transferKeeper) - // register the staking hooks - // NOTE: stakingKeeper above is passed by reference, so that it will contain these hooks - app.stakingKeeper = *stakingKeeper.SetHooks( - staking.NewMultiStakingHooks(app.distrKeeper.Hooks(), app.slashingKeeper.Hooks()), + // Create static IBC router, add transfer route, then set and seal it + ibcRouter := porttypes.NewRouter() + ibcRouter.AddRoute(ibctransfertypes.ModuleName, transferModule) + app.ibcKeeper.SetRouter(ibcRouter) + + // create evidence keeper with router + evidenceKeeper := evidencekeeper.NewKeeper( + appCodec, keys[evidencetypes.StoreKey], &app.stakingKeeper, app.slashingKeeper, ) + app.evidenceKeeper = *evidenceKeeper // just re-use the full router - do we want to limit this more? var wasmRouter = bApp.Router() - // better way to get this dir??? - homeDir := viper.GetString(cli.HomeFlag) - wasmDir := filepath.Join(homeDir, "wasm") + wasmDir := filepath.Join(homePath, "wasm") wasmWrap := WasmWrapper{Wasm: wasm.DefaultWasmConfig()} err := viper.Unmarshal(&wasmWrap) @@ -300,89 +365,144 @@ func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b // if we want to allow any custom callbacks supportedFeatures := "staking" app.wasmKeeper = wasm.NewKeeper( - app.cdc, keys[wasm.StoreKey], app.subspaces[wasm.ModuleName], app.accountKeeper, - app.bankKeeper, app.stakingKeeper, app.distrKeeper, wasmRouter, wasmDir, wasmConfig, - supportedFeatures, nil, nil) + appCodec, + keys[wasm.StoreKey], + app.getSubspace(wasm.ModuleName), + app.accountKeeper, + app.bankKeeper, + app.stakingKeeper, + app.distrKeeper, + wasmRouter, + wasmDir, + wasmConfig, + supportedFeatures, + nil, + nil, + ) // The gov proposal types can be individually enabled if len(enabledProposals) != 0 { govRouter.AddRoute(wasm.RouterKey, wasm.NewWasmProposalHandler(app.wasmKeeper, enabledProposals)) } - app.govKeeper = gov.NewKeeper( - app.cdc, keys[gov.StoreKey], app.subspaces[gov.ModuleName], - app.supplyKeeper, &stakingKeeper, govRouter, + app.govKeeper = govkeeper.NewKeeper( + appCodec, + keys[govtypes.StoreKey], + app.getSubspace(govtypes.ModuleName), + app.accountKeeper, + app.bankKeeper, + &stakingKeeper, + govRouter, ) // NOTE: Any module instantiated in the module manager that is later modified // must be passed by reference here. app.mm = module.NewManager( - genutil.NewAppModule(app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx), - auth.NewAppModule(app.accountKeeper), - bank.NewAppModule(app.bankKeeper, app.accountKeeper), + genutil.NewAppModule( + app.accountKeeper, app.stakingKeeper, app.BaseApp.DeliverTx, + encodingConfig.TxConfig), + auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts), + vesting.NewAppModule(app.accountKeeper, app.bankKeeper), + bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), + capability.NewAppModule(appCodec, *app.capabilityKeeper), crisis.NewAppModule(&app.crisisKeeper), - supply.NewAppModule(app.supplyKeeper, app.accountKeeper), - gov.NewAppModule(app.govKeeper, app.accountKeeper, app.supplyKeeper), - mint.NewAppModule(app.mintKeeper), - slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.stakingKeeper), - distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.supplyKeeper, app.stakingKeeper), - staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.supplyKeeper), - wasm.NewAppModule(app.wasmKeeper), + 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), + distr.NewAppModule(appCodec, app.distrKeeper, app.accountKeeper, app.bankKeeper, app.stakingKeeper), + staking.NewAppModule(appCodec, app.stakingKeeper, app.accountKeeper, app.bankKeeper), upgrade.NewAppModule(app.upgradeKeeper), - evidence.NewAppModule(*app.evidenceKeeper), + wasm.NewAppModule(app.wasmKeeper), + evidence.NewAppModule(app.evidenceKeeper), + ibc.NewAppModule(app.ibcKeeper), + params.NewAppModule(app.paramsKeeper), + transferModule, ) + // During begin block slashing happens after distr.BeginBlocker so that // there is nothing left over in the validator fee pool, so as to keep the // CanWithdrawInvariant invariant. - - app.mm.SetOrderBeginBlockers(upgrade.ModuleName, staking.ModuleName, mint.ModuleName, distr.ModuleName, slashing.ModuleName) - app.mm.SetOrderEndBlockers(crisis.ModuleName, gov.ModuleName, staking.ModuleName) + // NOTE: staking module is required if HistoricalEntries param > 0 + app.mm.SetOrderBeginBlockers( + upgradetypes.ModuleName, minttypes.ModuleName, distrtypes.ModuleName, slashingtypes.ModuleName, + evidencetypes.ModuleName, stakingtypes.ModuleName, ibchost.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. app.mm.SetOrderInitGenesis( - distr.ModuleName, staking.ModuleName, auth.ModuleName, bank.ModuleName, - slashing.ModuleName, gov.ModuleName, mint.ModuleName, supply.ModuleName, - crisis.ModuleName, genutil.ModuleName, evidence.ModuleName, wasm.ModuleName, + capabilitytypes.ModuleName, authtypes.ModuleName, distrtypes.ModuleName, stakingtypes.ModuleName, banktypes.ModuleName, + slashingtypes.ModuleName, govtypes.ModuleName, minttypes.ModuleName, crisistypes.ModuleName, + ibchost.ModuleName, genutiltypes.ModuleName, evidencetypes.ModuleName, ibctransfertypes.ModuleName, + wasm.ModuleName, ) - app.mm.RegisterInvariants(&app.crisisKeeper) - app.mm.RegisterRoutes(app.Router(), app.QueryRouter()) + 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 !!!! // create the simulation manager and define the order of the modules for deterministic simulations // - // NOTE: This is not required for apps that don't use the simulator for fuzz testing - // transactions. + // NOTE: this is not required apps that don't use the simulator for fuzz testing + // transactions app.sm = module.NewSimulationManager( - auth.NewAppModule(app.accountKeeper), - bank.NewAppModule(app.bankKeeper, app.accountKeeper), - supply.NewAppModule(app.supplyKeeper, app.accountKeeper), - gov.NewAppModule(app.govKeeper, app.accountKeeper, app.supplyKeeper), - mint.NewAppModule(app.mintKeeper), - distr.NewAppModule(app.distrKeeper, app.accountKeeper, app.supplyKeeper, app.stakingKeeper), - staking.NewAppModule(app.stakingKeeper, app.accountKeeper, app.supplyKeeper), - slashing.NewAppModule(app.slashingKeeper, app.accountKeeper, app.stakingKeeper), + auth.NewAppModule(appCodec, app.accountKeeper, authsims.RandomGenesisAccounts), + bank.NewAppModule(appCodec, app.bankKeeper, app.accountKeeper), + capability.NewAppModule(appCodec, *app.capabilityKeeper), + 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(app.wasmKeeper), + evidence.NewAppModule(app.evidenceKeeper), + ibc.NewAppModule(app.ibcKeeper), + transferModule, ) app.sm.RegisterStoreDecoders() // initialize stores app.MountKVStores(keys) - app.MountTransientStores(tKeys) + app.MountTransientStores(tkeys) + app.MountMemoryStores(memKeys) // initialize BaseApp app.SetInitChainer(app.InitChainer) app.SetBeginBlocker(app.BeginBlocker) - app.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper, app.supplyKeeper, auth.DefaultSigVerificationGasConsumer)) + app.SetAnteHandler( + ante.NewAnteHandler( + app.accountKeeper, app.bankKeeper, ante.DefaultSigVerificationGasConsumer, + encodingConfig.TxConfig.SignModeHandler(), + ), + ) app.SetEndBlocker(app.EndBlocker) if loadLatest { - err := app.LoadLatestVersion(app.keys[bam.MainStoreKey]) - if err != nil { + if err := app.LoadLatestVersion(); err != nil { tmos.Exit(err.Error()) } + + // 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 + ctx := app.BaseApp.NewUncachedContext(true, tmproto.Header{}) + app.capabilityKeeper.InitializeAndSeal(ctx) } + app.ScopedIBCKeeper = scopedIBCKeeper + app.ScopedTransferKeeper = scopedTransferKeeper + app.ScopedIBCKeeper = scopedIBCKeeper + return app } @@ -401,30 +521,42 @@ func (app *WasmApp) EndBlocker(ctx sdk.Context, req abci.RequestEndBlock) abci.R // InitChainer application update at chain initialization func (app *WasmApp) InitChainer(ctx sdk.Context, req abci.RequestInitChain) abci.ResponseInitChain { - var genesisState simapp.GenesisState - app.cdc.MustUnmarshalJSON(req.AppStateBytes, &genesisState) - - return app.mm.InitGenesis(ctx, genesisState) + var genesisState GenesisState + if err := tmjson.Unmarshal(req.AppStateBytes, &genesisState); err != nil { + panic(err) + } + return app.mm.InitGenesis(ctx, app.appCodec, genesisState) } // LoadHeight loads a particular height func (app *WasmApp) LoadHeight(height int64) error { - return app.LoadVersion(height, app.keys[bam.MainStoreKey]) + return app.LoadVersion(height) } // ModuleAccountAddrs returns all the app's module account addresses. func (app *WasmApp) ModuleAccountAddrs() map[string]bool { modAccAddrs := make(map[string]bool) for acc := range maccPerms { - modAccAddrs[supply.NewModuleAddress(acc).String()] = true + modAccAddrs[authtypes.NewModuleAddress(acc).String()] = true } return modAccAddrs } -// Codec returns the application's sealed codec. -func (app *WasmApp) Codec() *codec.Codec { - return app.cdc +// BlockedAddrs returns all the app's module account addresses that are not +// allowed to receive external tokens. +func (app *WasmApp) BlockedAddrs() map[string]bool { + blockedAddrs := make(map[string]bool) + for acc := range maccPerms { + blockedAddrs[authtypes.NewModuleAddress(acc).String()] = !allowedReceivingModAcc[acc] + } + + return blockedAddrs +} + +// LegacyAmino returns the application's sealed codec. +func (app *WasmApp) LegacyAmino() *codec.LegacyAmino { + return app.legacyAmino } // SimulationManager implements the SimulationApp interface @@ -432,11 +564,64 @@ func (app *WasmApp) SimulationManager() *module.SimulationManager { return app.sm } -// GetMaccPerms returns a mapping of the application's module account permissions. +// getSubspace returns a param subspace for a given module name. +// +// NOTE: This is solely to be used for testing purposes. +func (app *WasmApp) getSubspace(moduleName string) paramstypes.Subspace { + subspace, _ := app.paramsKeeper.GetSubspace(moduleName) + return subspace +} + +// RegisterAPIRoutes registers all application module routes with the provided +// API server. +func (app *WasmApp) RegisterAPIRoutes(apiSvr *api.Server, apiConfig config.APIConfig) { + clientCtx := apiSvr.ClientCtx + rpc.RegisterRoutes(clientCtx, apiSvr.Router) + authrest.RegisterTxRoutes(clientCtx, apiSvr.Router) + + ModuleBasics.RegisterRESTRoutes(clientCtx, apiSvr.Router) + ModuleBasics.RegisterGRPCRoutes(apiSvr.ClientCtx, apiSvr.GRPCRouter) + + // register swagger API from root so that other applications can override easily + if apiConfig.Swagger { + RegisterSwaggerAPI(clientCtx, apiSvr.Router) + } +} + +// RegisterSwaggerAPI registers swagger route with API Server +func RegisterSwaggerAPI(_ client.Context, rtr *mux.Router) { + statikFS, err := fs.New() + if err != nil { + panic(err) + } + + staticServer := http.FileServer(statikFS) + rtr.PathPrefix("/swagger/").Handler(http.StripPrefix("/swagger/", staticServer)) +} + +// GetMaccPerms returns a copy of the module account permissions func GetMaccPerms() map[string][]string { - modAccPerms := make(map[string][]string) + dupMaccPerms := make(map[string][]string) for k, v := range maccPerms { - modAccPerms[k] = v + dupMaccPerms[k] = v } - return modAccPerms + return dupMaccPerms +} + +// initParamsKeeper init params keeper and its subspaces +func initParamsKeeper(appCodec codec.BinaryMarshaler, legacyAmino *codec.LegacyAmino, key, tkey sdk.StoreKey) paramskeeper.Keeper { + paramsKeeper := paramskeeper.NewKeeper(appCodec, legacyAmino, key, tkey) + + paramsKeeper.Subspace(authtypes.ModuleName) + paramsKeeper.Subspace(banktypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName) + paramsKeeper.Subspace(minttypes.ModuleName) + paramsKeeper.Subspace(distrtypes.ModuleName) + paramsKeeper.Subspace(slashingtypes.ModuleName) + paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()) + paramsKeeper.Subspace(crisistypes.ModuleName) + paramsKeeper.Subspace(ibctransfertypes.ModuleName) + paramsKeeper.Subspace(wasm.ModuleName) + + return paramsKeeper } diff --git a/app/app_test.go b/app/app_test.go index 6acefa0992..7c4149bb8b 100644 --- a/app/app_test.go +++ b/app/app_test.go @@ -1,43 +1,46 @@ package app import ( - "github.com/magiconair/properties/assert" + "encoding/json" "os" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/tendermint/tendermint/libs/log" - - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/simapp" - abci "github.com/tendermint/tendermint/abci/types" db "github.com/tendermint/tm-db" "github.com/CosmWasm/wasmd/x/wasm" + abci "github.com/tendermint/tendermint/abci/types" ) func TestWasmdExport(t *testing.T) { db := db.NewMemDB() - gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0, wasm.EnableAllProposals, map[int64]bool{}) + gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, "", 0, wasm.EnableAllProposals) err := setGenesis(gapp) require.NoError(t, err) // 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, 0, wasm.EnableAllProposals, map[int64]bool{}) - _, _, err = newGapp.ExportAppStateAndValidators(false, []string{}) + newGapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, "", 0, wasm.EnableAllProposals) + _, err = newGapp.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err, "ExportAppStateAndValidators should not have an error") } // ensure that black listed addresses are properly set in bank keeper func TestBlackListedAddrs(t *testing.T) { db := db.NewMemDB() - gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0, wasm.EnableAllProposals, map[int64]bool{}) + gapp := NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, "", 0, wasm.EnableAllProposals) for acc := range maccPerms { - require.True(t, gapp.bankKeeper.BlacklistedAddr(gapp.supplyKeeper.GetModuleAddress(acc))) + require.Equal(t, !allowedReceivingModAcc[acc], gapp.bankKeeper.BlockedAddr(gapp.accountKeeper.GetModuleAddress(acc))) } } +func TestGetMaccPerms(t *testing.T) { + dup := GetMaccPerms() + require.Equal(t, maccPerms, dup, "duplicated module account permissions differed from actual module account permissions") +} + func TestGetEnabledProposals(t *testing.T) { cases := map[string]struct { proposalsEnabled string @@ -70,9 +73,8 @@ func TestGetEnabledProposals(t *testing.T) { } func setGenesis(gapp *WasmApp) error { - genesisState := simapp.NewDefaultGenesisState() - genesisState[wasm.ModuleName] = wasm.AppModuleBasic{}.DefaultGenesis() - stateBytes, err := codec.MarshalJSONIndent(gapp.Codec(), genesisState) + genesisState := NewDefaultGenesisState() + stateBytes, err := json.MarshalIndent(genesisState, "", " ") if err != nil { return err } diff --git a/app/benchmarks/txsize_test.go b/app/benchmarks/txsize_test.go deleted file mode 100644 index ce135ee2a4..0000000000 --- a/app/benchmarks/txsize_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package app - -import ( - "fmt" - - "github.com/tendermint/tendermint/crypto/secp256k1" - - "github.com/CosmWasm/wasmd/app" - - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" -) - -// This will fail half the time with the second output being 173 -// This is due to secp256k1 signatures not being constant size. -// nolint: vet -func ExampleTxSendSize() { - cdc := app.MakeCodec() - var gas uint64 = 1 - - priv1 := secp256k1.GenPrivKeySecp256k1([]byte{0}) - addr1 := sdk.AccAddress(priv1.PubKey().Address()) - priv2 := secp256k1.GenPrivKeySecp256k1([]byte{1}) - addr2 := sdk.AccAddress(priv2.PubKey().Address()) - coins := sdk.Coins{sdk.NewCoin("denom", sdk.NewInt(10))} - msg1 := bank.MsgMultiSend{ - Inputs: []bank.Input{bank.NewInput(addr1, coins)}, - Outputs: []bank.Output{bank.NewOutput(addr2, coins)}, - } - fee := auth.NewStdFee(gas, coins) - signBytes := auth.StdSignBytes("example-chain-ID", - 1, 1, fee, []sdk.Msg{msg1}, "") - sig, err := priv1.Sign(signBytes) - if err != nil { - return - } - sigs := []auth.StdSignature{{Signature: sig}} - tx := auth.NewStdTx([]sdk.Msg{msg1}, fee, sigs, "") - fmt.Println(len(cdc.MustMarshalBinaryBare([]sdk.Msg{msg1}))) - fmt.Println(len(cdc.MustMarshalBinaryBare(tx))) - // output: 80 - // 169 -} diff --git a/app/encoding.go b/app/encoding.go new file mode 100644 index 0000000000..1bd14b7827 --- /dev/null +++ b/app/encoding.go @@ -0,0 +1,37 @@ +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" +) + +// 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 +} + +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, + } +} diff --git a/app/export.go b/app/export.go index 21ffe0f94d..e58d68f1fc 100644 --- a/app/export.go +++ b/app/export.go @@ -4,53 +4,65 @@ import ( "encoding/json" "log" - abci "github.com/tendermint/tendermint/abci/types" - tmtypes "github.com/tendermint/tendermint/types" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - "github.com/cosmos/cosmos-sdk/codec" + servertypes "github.com/cosmos/cosmos-sdk/server/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/slashing" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) -// ExportAppStateAndValidators export the state of gaia for a genesis file -func (app *WasmApp) ExportAppStateAndValidators(forZeroHeight bool, jailWhiteList []string, -) (appState json.RawMessage, validators []tmtypes.GenesisValidator, err error) { +// ExportAppStateAndValidators exports the state of the application for a genesis +// file. +func (app *WasmApp) ExportAppStateAndValidators( + forZeroHeight bool, jailAllowedAddrs []string, +) (servertypes.ExportedApp, error) { // as if they could withdraw from the start of the next block - ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) + ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + // We export at last height + 1, because that's the height at which + // Tendermint will start InitChain. + height := app.LastBlockHeight() + 1 if forZeroHeight { - app.prepForZeroHeightGenesis(ctx, jailWhiteList) + height = 0 + app.prepForZeroHeightGenesis(ctx, jailAllowedAddrs) } - genState := app.mm.ExportGenesis(ctx) - appState, err = codec.MarshalJSONIndent(app.cdc, genState) + genState := app.mm.ExportGenesis(ctx, app.appCodec) + appState, err := json.MarshalIndent(genState, "", " ") if err != nil { - return nil, nil, err + return servertypes.ExportedApp{}, err } - validators = staking.WriteValidators(ctx, app.stakingKeeper) - return appState, validators, nil + + validators := staking.WriteValidators(ctx, app.stakingKeeper) + return servertypes.ExportedApp{ + AppState: appState, + Validators: validators, + Height: height, + ConsensusParams: app.BaseApp.GetConsensusParams(ctx), + }, nil } // prepare for fresh start at zero height // NOTE zero height genesis is a temporary feature which will be deprecated // in favour of export at a block height -func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []string) { - applyWhiteList := false +func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailAllowedAddrs []string) { + applyAllowedAddrs := false - //Check if there is a whitelist - if len(jailWhiteList) > 0 { - applyWhiteList = true + // check if there is a allowed address list + if len(jailAllowedAddrs) > 0 { + applyAllowedAddrs = true } - whiteListMap := make(map[string]bool) + allowedAddrsMap := make(map[string]bool) - for _, addr := range jailWhiteList { + for _, addr := range jailAllowedAddrs { _, err := sdk.ValAddressFromBech32(addr) if err != nil { log.Fatal(err) } - whiteListMap[addr] = true + allowedAddrsMap[addr] = true } /* Just to be safe, assert the invariants on current state. */ @@ -59,21 +71,24 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st /* Handle fee distribution state. */ // withdraw all validator commission - app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { - _, err := app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) - if err != nil { - log.Fatal(err) - } + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { + _, _ = app.distrKeeper.WithdrawValidatorCommission(ctx, val.GetOperator()) return false }) // withdraw all delegator rewards dels := app.stakingKeeper.GetAllDelegations(ctx) for _, delegation := range dels { - _, err := app.distrKeeper.WithdrawDelegationRewards(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) if err != nil { - log.Fatal(err) + panic(err) } + + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + panic(err) + } + _, _ = app.distrKeeper.WithdrawDelegationRewards(ctx, delAddr, valAddr) } // clear validator slash events @@ -87,10 +102,9 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st ctx = ctx.WithBlockHeight(0) // reinitialize all validators - app.stakingKeeper.IterateValidators(ctx, func(_ int64, val staking.ValidatorI) (stop bool) { - + app.stakingKeeper.IterateValidators(ctx, func(_ int64, val stakingtypes.ValidatorI) (stop bool) { // donate any unwithdrawn outstanding reward fraction tokens to the community pool - scraps := app.distrKeeper.GetValidatorOutstandingRewards(ctx, val.GetOperator()) + scraps := app.distrKeeper.GetValidatorOutstandingRewardsCoins(ctx, val.GetOperator()) feePool := app.distrKeeper.GetFeePool(ctx) feePool.CommunityPool = feePool.CommunityPool.Add(scraps...) app.distrKeeper.SetFeePool(ctx, feePool) @@ -101,8 +115,16 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st // reinitialize all delegations for _, del := range dels { - app.distrKeeper.Hooks().BeforeDelegationCreated(ctx, del.DelegatorAddress, del.ValidatorAddress) - app.distrKeeper.Hooks().AfterDelegationModified(ctx, del.DelegatorAddress, del.ValidatorAddress) + valAddr, err := sdk.ValAddressFromBech32(del.ValidatorAddress) + if err != nil { + panic(err) + } + delAddr, err := sdk.AccAddressFromBech32(del.DelegatorAddress) + if err != nil { + panic(err) + } + app.distrKeeper.Hooks().BeforeDelegationCreated(ctx, delAddr, valAddr) + app.distrKeeper.Hooks().AfterDelegationModified(ctx, delAddr, valAddr) } // reset context height @@ -111,7 +133,7 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st /* Handle staking state. */ // iterate through redelegations, reset creation height - app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red staking.Redelegation) (stop bool) { + app.stakingKeeper.IterateRedelegations(ctx, func(_ int64, red stakingtypes.Redelegation) (stop bool) { for i := range red.Entries { red.Entries[i].CreationHeight = 0 } @@ -120,7 +142,7 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st }) // iterate through unbonding delegations, reset creation height - app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd staking.UnbondingDelegation) (stop bool) { + app.stakingKeeper.IterateUnbondingDelegations(ctx, func(_ int64, ubd stakingtypes.UnbondingDelegation) (stop bool) { for i := range ubd.Entries { ubd.Entries[i].CreationHeight = 0 } @@ -130,8 +152,8 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st // Iterate through validators by power descending, reset bond heights, and // update bond intra-tx counters. - store := ctx.KVStore(app.keys[staking.StoreKey]) - iter := sdk.KVStoreReversePrefixIterator(store, staking.ValidatorsKey) + store := ctx.KVStore(app.keys[stakingtypes.StoreKey]) + iter := sdk.KVStoreReversePrefixIterator(store, stakingtypes.ValidatorsKey) counter := int16(0) for ; iter.Valid(); iter.Next() { @@ -142,7 +164,7 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st } validator.UnbondingHeight = 0 - if applyWhiteList && !whiteListMap[addr.String()] { + if applyAllowedAddrs && !allowedAddrsMap[addr.String()] { validator.Jailed = true } @@ -159,7 +181,7 @@ func (app *WasmApp) prepForZeroHeightGenesis(ctx sdk.Context, jailWhiteList []st // reset start height on signing infos app.slashingKeeper.IterateValidatorSigningInfos( ctx, - func(addr sdk.ConsAddress, info slashing.ValidatorSigningInfo) (stop bool) { + func(addr sdk.ConsAddress, info slashingtypes.ValidatorSigningInfo) (stop bool) { info.StartHeight = 0 app.slashingKeeper.SetValidatorSigningInfo(ctx, addr, info) return false diff --git a/app/genesis.go b/app/genesis.go index 97258ac992..a8d3a677a3 100644 --- a/app/genesis.go +++ b/app/genesis.go @@ -1,11 +1,14 @@ package app -import "encoding/json" +import ( + "encoding/json" +) // GenesisState defines a type alias for the Gaia genesis application state. type GenesisState map[string]json.RawMessage // NewDefaultGenesisState generates the default state for the application. func NewDefaultGenesisState() GenesisState { - return ModuleBasics.DefaultGenesis() + encCfg := MakeEncodingConfig() + return ModuleBasics.DefaultGenesis(encCfg.Marshaler) } diff --git a/app/integration/common_test.go b/app/integration/common_test.go index e2eae32cd8..b46ecb1b8f 100644 --- a/app/integration/common_test.go +++ b/app/integration/common_test.go @@ -6,20 +6,25 @@ This file is full of test helper functions, taken from simapp import ( "fmt" + "math/rand" "os" "testing" + "time" wasmd "github.com/CosmWasm/wasmd/app" "github.com/CosmWasm/wasmd/x/wasm" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" + "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/cosmos/cosmos-sdk/types/tx/signing" + authsign "github.com/cosmos/cosmos-sdk/x/auth/signing" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/libs/log" + tmtypes "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" ) @@ -32,12 +37,12 @@ const ( // Setup initializes a new wasmd.WasmApp. A Nop logger is set in WasmApp. func Setup(isCheckTx bool) *wasmd.WasmApp { db := dbm.NewMemDB() - app := wasmd.NewWasmApp(log.NewNopLogger(), db, nil, true, 0, wasm.EnableAllProposals, nil) + app := wasmd.NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, "", 0, wasm.EnableAllProposals) // app := wasmd.NewWasmApp(log.NewNopLogger(), db, nil, true, map[int64]bool{}, 0) if !isCheckTx { // init chain must be called to stop deliverState from being nil genesisState := wasmd.NewDefaultGenesisState() - stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState) + stateBytes, err := codec.MarshalJSONIndent(app.LegacyAmino(), genesisState) if err != nil { panic(err) } @@ -56,19 +61,18 @@ func Setup(isCheckTx bool) *wasmd.WasmApp { // SetupWithGenesisAccounts initializes a new wasmd.WasmApp with the passed in // genesis accounts. -func SetupWithGenesisAccounts(genAccs []authexported.GenesisAccount) *wasmd.WasmApp { +func SetupWithGenesisAccounts(genAccs []authtypes.GenesisAccount) *wasmd.WasmApp { db := dbm.NewMemDB() - app := wasmd.NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, 0, wasm.EnableAllProposals, nil) - // app := wasmd.NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, 0) + app := wasmd.NewWasmApp(log.NewTMLogger(log.NewSyncWriter(os.Stdout)), db, nil, true, map[int64]bool{}, "", 0, wasm.EnableAllProposals) // initialize the chain with the passed in genesis accounts genesisState := wasmd.NewDefaultGenesisState() - authGenesis := auth.NewGenesisState(auth.DefaultParams(), genAccs) - genesisStateBz := app.Codec().MustMarshalJSON(authGenesis) - genesisState[auth.ModuleName] = genesisStateBz + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisStateBz := app.LegacyAmino().MustMarshalJSON(authGenesis) + genesisState[authtypes.ModuleName] = genesisStateBz - stateBytes, err := codec.MarshalJSONIndent(app.Codec(), genesisState) + stateBytes, err := codec.MarshalJSONIndent(app.LegacyAmino(), genesisState) if err != nil { panic(err) } @@ -83,7 +87,7 @@ func SetupWithGenesisAccounts(genAccs []authexported.GenesisAccount) *wasmd.Wasm ) app.Commit() - app.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{Height: app.LastBlockHeight() + 1, ChainID: SimAppChainID}}) + app.BeginBlock(abci.RequestBeginBlock{Header: tmtypes.Header{Height: app.LastBlockHeight() + 1, ChainID: SimAppChainID}}) return app } @@ -93,11 +97,12 @@ func SetupWithGenesisAccounts(genAccs []authexported.GenesisAccount) *wasmd.Wasm // the parameter 'expPass' against the result. A corresponding result is // returned. func SignAndDeliver( - t *testing.T, app *wasmd.WasmApp, msgs []sdk.Msg, + t *testing.T, txCfg client.TxConfig, app *wasmd.WasmApp, msgs []sdk.Msg, accNums, seq []uint64, expPass bool, priv ...crypto.PrivKey, ) (sdk.GasInfo, *sdk.Result, error) { - - tx := GenTx( + t.Helper() + tx, err := GenTx( + wasmd.MakeEncodingConfig().TxConfig, msgs, sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, DefaultGenTxGas, @@ -106,11 +111,11 @@ func SignAndDeliver( seq, priv..., ) - + require.NoError(t, err) // Simulate a sending a transaction and committing a block - app.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{Height: app.LastBlockHeight() + 1, ChainID: SimAppChainID}}) + app.BeginBlock(abci.RequestBeginBlock{Header: tmtypes.Header{Height: app.LastBlockHeight() + 1, ChainID: SimAppChainID}}) - gasInfo, res, err := app.Deliver(tx) + gasInfo, res, err := app.Deliver(txCfg.TxEncoder(), tx) if expPass { require.NoError(t, err) require.NotNil(t, res) @@ -126,27 +131,58 @@ func SignAndDeliver( } // GenTx generates a signed mock transaction. -func GenTx(msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) auth.StdTx { - fee := auth.StdFee{ - Amount: feeAmt, - Gas: gas, - } +func GenTx(gen client.TxConfig, msgs []sdk.Msg, feeAmt sdk.Coins, gas uint64, chainID string, accnums []uint64, seq []uint64, priv ...crypto.PrivKey) (sdk.Tx, error) { + sigs := make([]signing.SignatureV2, len(priv)) + + // create a random length memo + r := rand.New(rand.NewSource(time.Now().UnixNano())) + + memo := simulation.RandStringOfLength(r, simulation.RandIntBetween(r, 0, 100)) - sigs := make([]auth.StdSignature, len(priv)) + signMode := gen.SignModeHandler().DefaultMode() + + for i, p := range priv { + sigs[i] = signing.SignatureV2{ + PubKey: p.PubKey(), + Data: &signing.SingleSignatureData{ + SignMode: signMode, + }, + } + } - memo := "Test tx" + tx := gen.NewTxBuilder() + err := tx.SetMsgs(msgs...) + if err != nil { + return nil, err + } + err = tx.SetSignatures(sigs...) + if err != nil { + return nil, err + } + tx.SetMemo(memo) + tx.SetFeeAmount(feeAmt) + tx.SetGasLimit(gas) for i, p := range priv { // use a empty chainID for ease of testing - sig, err := p.Sign(auth.StdSignBytes(chainID, accnums[i], seq[i], fee, msgs, memo)) + signerData := authsign.SignerData{ + ChainID: chainID, + AccountNumber: accnums[i], + Sequence: seq[i], + } + signBytes, err := gen.SignModeHandler().GetSignBytes(signMode, signerData, tx.GetTx()) if err != nil { panic(err) } - - sigs[i] = auth.StdSignature{ - PubKey: p.PubKey(), - Signature: sig, + sig, err := p.Sign(signBytes) + if err != nil { + panic(err) + } + sigs[i].Data.(*signing.SingleSignatureData).Signature = sig + err = tx.SetSignatures(sigs...) + if err != nil { + panic(err) } } - return auth.NewStdTx(msgs, fee, sigs, memo) + return tx.GetTx(), nil } diff --git a/app/integration/integration_test.go b/app/integration/integration_test.go index 305df6292f..bf789fac32 100644 --- a/app/integration/integration_test.go +++ b/app/integration/integration_test.go @@ -6,24 +6,18 @@ import ( "testing" "github.com/CosmWasm/wasmd/app" - "github.com/stretchr/testify/require" - + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authExported "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/bank" - + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/tendermint/tendermint/crypto" - - // "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/secp256k1" ) // CreateTestApp will create a new wasmd application and provide money to every address // listed there -func CreateTestApp(t *testing.T, accounts []*auth.BaseAccount) *app.WasmApp { +func CreateTestApp(t *testing.T, accounts []*authtypes.BaseAccount) *app.WasmApp { fmt.Printf("%#v\n", accounts[1]) - genAccounts := make([]authExported.GenesisAccount, len(accounts)) + genAccounts := make([]authtypes.GenesisAccount, len(accounts)) for i, acct := range accounts { genAccounts[i] = acct } @@ -41,16 +35,17 @@ func TestSendWithApp(t *testing.T) { wasm := CreateTestApp(t, accts) // TODO: check account balance first - msg := bank.MsgSend{ + msg := banktypes.MsgSend{ FromAddress: accts[0].Address, ToAddress: accts[1].Address, Amount: sdk.NewCoins(sdk.NewInt64Coin("stake", 20)), } - _ = sign(t, wasm, msg, &keys[0], true) + _ = sign(t, wasm, &msg, &keys[0], true) } func sign(t *testing.T, wasm *app.WasmApp, msg sdk.Msg, signer *signer, expectPass bool) *sdk.Result { - _, res, _ := SignAndDeliver(t, wasm, []sdk.Msg{msg}, []uint64{signer.acctNum}, []uint64{signer.seq}, expectPass, signer.priv) + txGen := app.MakeEncodingConfig().TxConfig + _, res, _ := SignAndDeliver(t, txGen, wasm, []sdk.Msg{msg}, []uint64{signer.acctNum}, []uint64{signer.seq}, expectPass, signer.priv) if expectPass { signer.seq++ } @@ -63,27 +58,29 @@ type signer struct { acctNum uint64 } -func genAccountsWithKey(t *testing.T, coins sdk.Coins, n int) ([]*auth.BaseAccount, []signer) { - accts := make([]*auth.BaseAccount, n) - keys := make([]signer, n) - - for i := range accts { - priv, pub, addr := maskKeyPubAddr() - baseAcct := auth.NewBaseAccountWithAddress(addr) - err := baseAcct.SetCoins(coins) - require.NoError(t, err) - baseAcct.SetPubKey(pub) - baseAcct.SetAccountNumber(uint64(i + 1)) - baseAcct.SetSequence(1) - accts[i] = &baseAcct - keys[i] = signer{ - priv: priv, - acctNum: baseAcct.GetAccountNumber(), - seq: baseAcct.GetSequence(), - } - } - - return accts, keys +func genAccountsWithKey(t *testing.T, coins sdk.Coins, n int) ([]*authtypes.BaseAccount, []signer) { + //accts := make([]*authtypes.BaseAccount, n) + //keys := make([]signer, n) + // + //for i := range accts { + // priv, pub, addr := maskKeyPubAddr() + // baseAcct := authtypes.NewBaseAccountWithAddress(addr) + // err := baseAcct.SetCoins(coins) + // require.NoError(t, err) + // baseAcct.SetPubKey(pub) + // baseAcct.SetAccountNumber(uint64(i + 1)) + // baseAcct.SetSequence(1) + // accts[i] = &baseAcct + // keys[i] = signer{ + // priv: priv, + // acctNum: baseAcct.GetAccountNumber(), + // seq: baseAcct.GetSequence(), + // } + //} + // + //return accts, keys + t.Fatal("not implemented") + return nil, nil } var maskKeyCounter uint64 = 0 @@ -95,7 +92,7 @@ func maskKeyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { seed := make([]byte, 8) binary.BigEndian.PutUint64(seed, maskKeyCounter) - key := secp256k1.GenPrivKeySecp256k1(seed) + key := secp256k1.GenPrivKeyFromSecret(seed) pub := key.PubKey() addr := sdk.AccAddress(pub.Address()) return key, pub, addr diff --git a/app/sim_bench_test.go b/app/sim_bench_test.go index fe40b2b5a7..bef8dac71d 100644 --- a/app/sim_bench_test.go +++ b/app/sim_bench_test.go @@ -5,10 +5,12 @@ import ( "os" "testing" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + "github.com/CosmWasm/wasmd/x/wasm" "github.com/cosmos/cosmos-sdk/simapp" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" "github.com/cosmos/cosmos-sdk/x/simulation" - abci "github.com/tendermint/tendermint/abci/types" ) // Profile with: @@ -27,13 +29,18 @@ func BenchmarkFullAppSimulation(b *testing.B) { } }() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm.EnableAllProposals, map[int64]bool{}, interBlockCacheOpt()) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, interBlockCacheOpt()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + b, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) // export state and simParams before the simulation error is checked @@ -66,13 +73,18 @@ func BenchmarkInvariants(b *testing.B) { } }() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm.EnableAllProposals, map[int64]bool{}, interBlockCacheOpt()) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, interBlockCacheOpt()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - b, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + b, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) // export state and simParams before the simulation error is checked @@ -88,7 +100,7 @@ func BenchmarkInvariants(b *testing.B) { simapp.PrintStats(db) } - ctx := app.NewContext(true, abci.Header{Height: app.LastBlockHeight() + 1}) + ctx := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight() + 1}) // 3. Benchmark each invariant separately // diff --git a/app/sim_test.go b/app/sim_test.go index fde219c32a..1f1ef405ae 100644 --- a/app/sim_test.go +++ b/app/sim_test.go @@ -7,10 +7,11 @@ import ( "os" "testing" - wasm2 "github.com/CosmWasm/wasmd/x/wasm" + "github.com/CosmWasm/wasmd/x/wasm" "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" "github.com/cosmos/cosmos-sdk/baseapp" @@ -18,17 +19,23 @@ import ( "github.com/cosmos/cosmos-sdk/simapp/helpers" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/params" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + 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" + 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" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" "github.com/cosmos/cosmos-sdk/x/simulation" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) +// Get flags every time the simulator is run func init() { simapp.GetSimulatorFlags() } @@ -63,14 +70,19 @@ func TestFullAppSimulation(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, fauxMerkleModeOpt) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, fauxMerkleModeOpt) require.Equal(t, appName, app.Name()) // run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + t, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) // export state and simParams before the simulation error is checked @@ -95,14 +107,19 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, fauxMerkleModeOpt) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, fauxMerkleModeOpt) require.Equal(t, appName, app.Name()) // Run randomized simulation _, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + t, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) // export state and simParams before the simulation error is checked @@ -116,7 +133,7 @@ func TestAppImportExport(t *testing.T) { fmt.Printf("exporting genesis...\n") - appState, _, err := app.ExportAppStateAndValidators(false, []string{}) + exported, err := app.ExportAppStateAndValidators(false, []string{}) require.NoError(t, err) fmt.Printf("importing genesis...\n") @@ -129,32 +146,37 @@ func TestAppImportExport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewWasmApp(log.NewNopLogger(), newDB, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, fauxMerkleModeOpt) + newApp := NewWasmApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, fauxMerkleModeOpt) require.Equal(t, appName, newApp.Name()) var genesisState GenesisState - err = app.Codec().UnmarshalJSON(appState, &genesisState) + err = json.Unmarshal(exported.AppState, &genesisState) require.NoError(t, err) - ctxA := app.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) - ctxB := newApp.NewContext(true, abci.Header{Height: app.LastBlockHeight()}) - newApp.mm.InitGenesis(ctxB, genesisState) + ctxA := app.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + ctxB := newApp.NewContext(true, tmproto.Header{Height: app.LastBlockHeight()}) + newApp.mm.InitGenesis(ctxB, app.appCodec, genesisState) + newApp.StoreConsensusParams(ctxB, exported.ConsensusParams) fmt.Printf("comparing stores...\n") storeKeysPrefixes := []StoreKeysPrefixes{ - {app.keys[baseapp.MainStoreKey], newApp.keys[baseapp.MainStoreKey], [][]byte{}}, - {app.keys[auth.StoreKey], newApp.keys[auth.StoreKey], [][]byte{}}, - {app.keys[staking.StoreKey], newApp.keys[staking.StoreKey], + {app.keys[authtypes.StoreKey], newApp.keys[authtypes.StoreKey], [][]byte{}}, + {app.keys[stakingtypes.StoreKey], newApp.keys[stakingtypes.StoreKey], [][]byte{ - staking.UnbondingQueueKey, staking.RedelegationQueueKey, staking.ValidatorQueueKey, + stakingtypes.UnbondingQueueKey, stakingtypes.RedelegationQueueKey, stakingtypes.ValidatorQueueKey, + stakingtypes.HistoricalInfoKey, }}, // ordering may change but it doesn't matter - {app.keys[slashing.StoreKey], newApp.keys[slashing.StoreKey], [][]byte{}}, - {app.keys[mint.StoreKey], newApp.keys[mint.StoreKey], [][]byte{}}, - {app.keys[distr.StoreKey], newApp.keys[distr.StoreKey], [][]byte{}}, - {app.keys[supply.StoreKey], newApp.keys[supply.StoreKey], [][]byte{}}, - {app.keys[params.StoreKey], newApp.keys[params.StoreKey], [][]byte{}}, - {app.keys[gov.StoreKey], newApp.keys[gov.StoreKey], [][]byte{}}, + {app.keys[slashingtypes.StoreKey], newApp.keys[slashingtypes.StoreKey], [][]byte{}}, + {app.keys[minttypes.StoreKey], newApp.keys[minttypes.StoreKey], [][]byte{}}, + {app.keys[distrtypes.StoreKey], newApp.keys[distrtypes.StoreKey], [][]byte{}}, + {app.keys[banktypes.StoreKey], newApp.keys[banktypes.StoreKey], [][]byte{banktypes.BalancesPrefix}}, + {app.keys[paramtypes.StoreKey], newApp.keys[paramtypes.StoreKey], [][]byte{}}, + {app.keys[govtypes.StoreKey], newApp.keys[govtypes.StoreKey], [][]byte{}}, + {app.keys[evidencetypes.StoreKey], newApp.keys[evidencetypes.StoreKey], [][]byte{}}, + {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{}}, } for _, skp := range storeKeysPrefixes { @@ -164,8 +186,8 @@ 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 key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) - require.Equal(t, len(failedKVAs), 0, simapp.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, app.Codec(), failedKVAs, failedKVBs)) + fmt.Printf("compared %d different key/value pairs between %s and %s\n", len(failedKVAs), skp.A, skp.B) + require.Equal(t, len(failedKVAs), 0, simapp.GetSimulationLog(skp.A.Name(), app.SimulationManager().StoreDecoders, failedKVAs, failedKVBs)) } } @@ -181,14 +203,19 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(dir)) }() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, fauxMerkleModeOpt) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, fauxMerkleModeOpt) require.Equal(t, appName, app.Name()) // Run randomized simulation stopEarly, simParams, simErr := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + t, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) // export state and simParams before the simulation error is checked @@ -207,7 +234,7 @@ func TestAppSimulationAfterImport(t *testing.T) { fmt.Printf("exporting genesis...\n") - appState, _, err := app.ExportAppStateAndValidators(true, []string{}) + exported, err := app.ExportAppStateAndValidators(true, []string{}) require.NoError(t, err) fmt.Printf("importing genesis...\n") @@ -220,17 +247,22 @@ func TestAppSimulationAfterImport(t *testing.T) { require.NoError(t, os.RemoveAll(newDir)) }() - newApp := NewWasmApp(log.NewNopLogger(), newDB, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, fauxMerkleModeOpt) + newApp := NewWasmApp(log.NewNopLogger(), newDB, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, fauxMerkleModeOpt) require.Equal(t, appName, newApp.Name()) newApp.InitChain(abci.RequestInitChain{ - AppStateBytes: appState, + AppStateBytes: exported.AppState, }) _, _, err = simulation.SimulateFromSeed( - t, os.Stdout, newApp.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(newApp, newApp.Codec(), config), - newApp.ModuleAccountAddrs(), config, + t, + os.Stdout, + newApp.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(newApp, newApp.appCodec, config), + newApp.ModuleAccountAddrs(), + config, ) require.NoError(t, err) } @@ -264,7 +296,7 @@ func TestAppStateDeterminism(t *testing.T) { db := dbm.NewMemDB() - app := NewWasmApp(logger, db, nil, true, simapp.FlagPeriodValue, wasm2.EnableAllProposals, map[int64]bool{}, interBlockCacheOpt()) + app := NewWasmApp(logger, db, nil, true, map[int64]bool{}, "", simapp.FlagPeriodValue, wasm.EnableAllProposals, interBlockCacheOpt()) fmt.Printf( "running non-determinism simulation; seed %d: %d/%d, attempt: %d/%d\n", @@ -272,9 +304,14 @@ func TestAppStateDeterminism(t *testing.T) { ) _, _, err := simulation.SimulateFromSeed( - t, os.Stdout, app.BaseApp, simapp.AppStateFn(app.Codec(), app.SimulationManager()), - simapp.SimulationOperations(app, app.Codec(), config), - app.ModuleAccountAddrs(), config, + t, + os.Stdout, + app.BaseApp, + simapp.AppStateFn(app.appCodec, app.SimulationManager()), + simtypes.RandomAccounts, // Replace with own random account function if using keys other than secp256k1 + simapp.SimulationOperations(app, app.appCodec, config), + app.ModuleAccountAddrs(), + config, ) require.NoError(t, err) @@ -287,7 +324,7 @@ func TestAppStateDeterminism(t *testing.T) { if j != 0 { require.Equal( - t, appHashList[0], appHashList[j], + t, string(appHashList[0]), string(appHashList[j]), "non-determinism in seed %d: %d/%d, attempt: %d/%d\n", config.Seed, i+1, numSeeds, j+1, numTimesToRunPerSeed, ) } diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000000..8507c9cd41 --- /dev/null +++ b/buf.yaml @@ -0,0 +1,19 @@ +build: + roots: + - . +lint: + use: + - DEFAULT + - COMMENTS + - FILE_LOWER_SNAKE_CASE + except: + - UNARY_RPC + - COMMENT_FIELD + - PACKAGE_DIRECTORY_MATCH + ignore: + - third_party +breaking: + use: + - FILE + ignore: + - third_party diff --git a/cli_test/README.md b/cli_test/README.md deleted file mode 100644 index 7cc84d1de3..0000000000 --- a/cli_test/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# Gaia CLI Integration tests - -The gaia cli integration tests live in this folder. You can run the full suite by running: - -```bash -go test -mod=readonly -p 4 `go list ./cli_test/...` -tags=cli_test -``` - -> NOTE: While the full suite runs in parallel, some of the tests can take up to a minute to complete - -### Test Structure - -This integration suite [uses a thin wrapper](https://godoc.org/github.com/cosmos/cosmos-sdk/tests) over the [`os/exec`](https://golang.org/pkg/os/exec/) package. This allows the integration test to run against built binaries (both `wasmd` and `wasmcli` are used) while being written in golang. This allows tests to take advantage of the various golang code we have for operations like marshal/unmarshal, crypto, etc... - -> NOTE: The tests will use whatever `wasmd` or `wasmcli` binaries are available in your `$PATH`. You can check which binary will be run by the suite by running `which wasmd` or `which wasmcli`. If you have your `$GOPATH` properly setup they should be in `$GOPATH/bin/gaia*`. This will ensure that your test uses the latest binary you have built - -Tests generally follow this structure: - -```go -func TestMyNewCommand(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - // Your test code goes here... - - f.Cleanup() -} -``` - -This boilerplate above: - -- Ensures the tests run in parallel. Because the tests are calling out to `os/exec` for many operations these tests can take a long time to run. -- Creates `.wasmd` and `.wasmcli` folders in a new temp folder. -- Uses `wasmcli` to create 2 accounts for use in testing: `foo` and `bar` -- Creates a genesis file with coins (`1000footoken,1000feetoken,150stake`) controlled by the `foo` key -- Generates an initial bonding transaction (`gentx`) to make the `foo` key a validator at genesis -- Starts `wasmd` and stops it once the test exits -- Cleans up test state on a successful run - -### Notes when adding/running tests - -- Because the tests run against a built binary, you should make sure you build every time the code changes and you want to test again, otherwise you will be testing against an older version. If you are adding new tests this can easily lead to confusing test results. -- The [`test_helpers.go`](./test_helpers.go) file is organized according to the format of `wasmcli` and `wasmd` commands. There are comments with section headers describing the different areas. Helper functions to call CLI functionality are generally named after the command (e.g. `wasmcli query staking validator` would be `QueryStakingValidator`). Try to keep functions grouped by their position in the command tree. -- Test state that is needed by `tx` and `query` commands (`home`, `chain_id`, etc...) is stored on the `Fixtures` object. This makes constructing your new tests almost trivial. -- Sometimes if you exit a test early there can be still running `wasmd` and `wasmcli` processes that will interrupt subsequent runs. Still running `wasmcli` processes will block access to the keybase while still running `wasmd` processes will block ports and prevent new tests from spinning up. You can ensure new tests spin up clean by running `pkill -9 wasmd && pkill -9 wasmcli` before each test run. -- Most `query` and `tx` commands take a variadic `flags` argument. This pattern allows for the creation of a general function which is easily modified by adding flags. See the `TxSend` function and its use for a good example. -- `Tx*` functions follow a general pattern and return `(success bool, stdout string, stderr string)`. This allows for easy testing of multiple different flag configurations. See `TestGaiaCLICreateValidator` or `TestGaiaCLISubmitProposal` for a good example of the pattern. diff --git a/cli_test/cli_test.go b/cli_test/cli_test.go deleted file mode 100644 index 1241210785..0000000000 --- a/cli_test/cli_test.go +++ /dev/null @@ -1,1317 +0,0 @@ -// +build cli_test - -package clitest - -import ( - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - "testing" - - "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/crypto/ed25519" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - - "github.com/CosmWasm/wasmd/app" -) - -func TestGaiaCLIKeysAddMultisig(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // key names order does not matter - f.KeysAdd("msig1", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBar, keyBaz)) - f.KeysAdd("msig2", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBaz, keyBar)) - require.Equal(t, f.KeysShow("msig1").Address, f.KeysShow("msig2").Address) - - f.KeysAdd("msig3", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBar, keyBaz), - "--nosort") - f.KeysAdd("msig4", "--multisig-threshold=2", - fmt.Sprintf("--multisig=%s,%s", keyBaz, keyBar), - "--nosort") - require.NotEqual(t, f.KeysShow("msig3").Address, f.KeysShow("msig4").Address) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIKeysAddRecover(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - exitSuccess, _, _ := f.KeysAddRecover("empty-mnemonic", "") - require.False(t, exitSuccess) - - exitSuccess, _, _ = f.KeysAddRecover("test-recover", "dentist task convince chimney quality leave banana trade firm crawl eternal easily") - require.True(t, exitSuccess) - require.Equal(t, "cosmos1qcfdf69js922qrdr4yaww3ax7gjml6pdds46f4", f.KeyAddress("test-recover").String()) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIKeysAddRecoverHDPath(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - f.KeysAddRecoverHDPath("test-recoverHD1", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 0, 0) - require.Equal(t, "cosmos1qcfdf69js922qrdr4yaww3ax7gjml6pdds46f4", f.KeyAddress("test-recoverHD1").String()) - - f.KeysAddRecoverHDPath("test-recoverH2", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 5) - require.Equal(t, "cosmos1pdfav2cjhry9k79nu6r8kgknnjtq6a7rykmafy", f.KeyAddress("test-recoverH2").String()) - - f.KeysAddRecoverHDPath("test-recoverH3", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 1, 17) - require.Equal(t, "cosmos1909k354n6wl8ujzu6kmh49w4d02ax7qvlkv4sn", f.KeyAddress("test-recoverH3").String()) - - f.KeysAddRecoverHDPath("test-recoverH4", "dentist task convince chimney quality leave banana trade firm crawl eternal easily", 2, 17) - require.Equal(t, "cosmos1v9plmhvyhgxk3th9ydacm7j4z357s3nhtwsjat", f.KeyAddress("test-recoverH4").String()) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIMinimumFees(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - fees := fmt.Sprintf( - "--minimum-gas-prices=%s,%s", - sdk.NewDecCoinFromDec(feeDenom, minGasPrice), - sdk.NewDecCoinFromDec(fee2Denom, minGasPrice), - ) - proc := f.GDStart(fees) - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - - // Send a transaction that will get rejected - success, stdOut, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fee2Denom, 10), "-y") - require.Contains(t, stdOut, "insufficient fees") - require.True(f.T, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure tx w/ correct fees pass - txFees := fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)) - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fee2Denom, 10), txFees, "-y") - require.True(f.T, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure tx w/ improper fees fails - txFees = fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 1)) - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 10), txFees, "-y") - require.Contains(t, stdOut, "insufficient fees") - require.True(f.T, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIGasPrices(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - proc := f.GDStart(fmt.Sprintf("--minimum-gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice))) - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - - // insufficient gas prices (tx fails) - badGasPrice, _ := sdk.NewDecFromStr("0.000003") - success, stdOut, _ := f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 50), - fmt.Sprintf("--gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, badGasPrice)), "-y") - require.Contains(t, stdOut, "insufficient fees") - require.True(t, success) - - // wait for a block confirmation - tests.WaitForNextNBlocksTM(1, f.Port) - - // sufficient gas prices (tx passes) - success, _, _ = f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 50), - fmt.Sprintf("--gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice)), "-y") - require.True(t, success) - - // wait for a block confirmation - tests.WaitForNextNBlocksTM(1, f.Port) - - f.Cleanup() -} - -func TestGaiaCLIFeesDeduction(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - minGasPrice, _ := sdk.NewDecFromStr("0.000006") - proc := f.GDStart(fmt.Sprintf("--minimum-gas-prices=%s", sdk.NewDecCoinFromDec(feeDenom, minGasPrice))) - defer proc.Stop(false) - - // Save key addresses for later use - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - fooAmt := fooAcc.GetCoins().AmountOf(fooDenom) - - // test simulation - success, _, _ := f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 1000), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "--dry-run") - require.True(t, success) - - // Wait for a block - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, fooAmt.Int64(), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) - - // insufficient funds (coins + fees) tx fails - largeCoins := sdk.TokensFromConsensusPower(10000000) - success, stdOut, _ := f.TxSend( - keyFoo, barAddr, sdk.NewCoin(fooDenom, largeCoins), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "-y") - require.Contains(t, stdOut, "insufficient account funds") - require.True(t, success) - - // Wait for a block - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, fooAmt.Int64(), fooAcc.GetCoins().AmountOf(fooDenom).Int64()) - - // test success (transfer = coins + fees) - success, _, _ = f.TxSend( - keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, 500), - fmt.Sprintf("--fees=%s", sdk.NewInt64Coin(feeDenom, 2)), "-y") - require.True(t, success) - - f.Cleanup() -} - -func TestGaiaCLISend(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - // Save key addresses for later use - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Send some tokens from one account to the other - sendTokens := sdk.TokensFromConsensusPower(10) - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc := f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - // Test --dry-run - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--dry-run") - require.True(t, success) - - // Test --generate-only - success, stdout, stderr := f.TxSend( - fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only=true", - ) - require.Empty(t, stderr) - require.True(t, success) - msg := unmarshalStdTx(f.T, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Len(t, msg.Msgs, 1) - require.Len(t, msg.GetSignatures(), 0) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - // test autosequencing - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.MulRaw(2), barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens.MulRaw(2)), fooAcc.GetCoins().AmountOf(denom)) - - // test memo - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--memo='testmemo'", "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.MulRaw(3), barAcc.GetCoins().AmountOf(denom)) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens.MulRaw(3)), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLIGasAuto(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with auto gas disabled and very little gas set by hand - sendTokens := sdk.TokensFromConsensusPower(10) - success, stdOut, _ := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=10", "-y") - require.Contains(t, stdOut, "out of gas in location") - require.True(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with negative gas - success, _, _ = f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=-100", "-y") - require.False(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test failure with 0 gas - success, stdOut, _ = f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=0", "-y") - require.Contains(t, stdOut, "out of gas in location") - require.True(t, success) - - // Check state didn't change - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Enable auto gas - success, stdout, stderr := f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "--gas=auto", "-y") - require.NotEmpty(t, stderr) - require.True(t, success) - cdc := app.MakeCodec() - sendResp := sdk.TxResponse{} - err := cdc.UnmarshalJSON([]byte(stdout), &sendResp) - require.Nil(t, err) - require.True(t, sendResp.GasWanted >= sendResp.GasUsed) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Check state has changed accordingly - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLICreateValidator(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - barAddr := f.KeyAddress(keyBar) - barVal := sdk.ValAddress(barAddr) - - consPubKey := sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, ed25519.GenPrivKey().PubKey()) - - sendTokens := sdk.TokensFromConsensusPower(10) - f.TxSend(keyFoo, barAddr, sdk.NewCoin(denom, sendTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - barAcc := f.QueryAccount(barAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - - // Generate a create validator transaction and ensure correctness - success, stdout, stderr := f.TxStakingCreateValidator(barAddr.String(), consPubKey, sdk.NewInt64Coin(denom, 2), "--generate-only") - - require.True(f.T, success) - require.Empty(f.T, stderr) - msg := unmarshalStdTx(f.T, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test --dry-run - newValTokens := sdk.TokensFromConsensusPower(2) - success, _, _ = f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewCoin(denom, newValTokens), "--dry-run") - require.True(t, success) - - // Create the validator - f.TxStakingCreateValidator(keyBar, consPubKey, sdk.NewCoin(denom, newValTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure funds were deducted properly - barAcc = f.QueryAccount(barAddr) - require.Equal(t, sendTokens.Sub(newValTokens), barAcc.GetCoins().AmountOf(denom)) - - // Ensure that validator state is as expected - validator := f.QueryStakingValidator(barVal) - require.Equal(t, validator.OperatorAddress, barVal) - require.True(sdk.IntEq(t, newValTokens, validator.Tokens)) - - // Query delegations to the validator - validatorDelegations := f.QueryStakingDelegationsTo(barVal) - require.Len(t, validatorDelegations, 1) - require.NotZero(t, validatorDelegations[0].Shares) - - // unbond a single share - unbondAmt := sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(1)) - success = f.TxStakingUnbond(keyBar, unbondAmt.String(), barVal, "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure bonded staking is correct - remainingTokens := newValTokens.Sub(unbondAmt.Amount) - validator = f.QueryStakingValidator(barVal) - require.Equal(t, remainingTokens, validator.Tokens) - - // Get unbonding delegations from the validator - validatorUbds := f.QueryStakingUnbondingDelegationsFrom(barVal) - require.Len(t, validatorUbds, 1) - require.Len(t, validatorUbds[0].Entries, 1) - require.Equal(t, remainingTokens.String(), validatorUbds[0].Entries[0].Balance.String()) - - f.Cleanup() -} - -func TestGaiaCLIQueryRewards(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - cdc := app.MakeCodec() - - genesisState := f.GenesisState() - inflationMin := sdk.MustNewDecFromStr("1.0") - var mintData mint.GenesisState - cdc.UnmarshalJSON(genesisState[mint.ModuleName], &mintData) - mintData.Minter.Inflation = inflationMin - mintData.Params.InflationMin = inflationMin - mintData.Params.InflationMax = sdk.MustNewDecFromStr("1.0") - mintDataBz, err := cdc.MarshalJSON(mintData) - require.NoError(t, err) - genesisState[mint.ModuleName] = mintDataBz - - genFile := filepath.Join(f.GaiadHome, "config", "genesis.json") - genDoc, err := tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - genDoc.AppState, err = cdc.MarshalJSON(genesisState) - require.NoError(t, genDoc.SaveAs(genFile)) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - rewards := f.QueryRewards(fooAddr) - require.Equal(t, 1, len(rewards.Rewards)) - - f.Cleanup() -} - -func TestGaiaCLIQuerySupply(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - totalSupply := f.QueryTotalSupply() - totalSupplyOf := f.QueryTotalSupplyOf(fooDenom) - - require.Equal(t, totalCoins, totalSupply) - require.True(sdk.IntEq(t, totalCoins.AmountOf(fooDenom), totalSupplyOf)) - - f.Cleanup() -} - -func TestGaiaCLISubmitProposal(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - f.QueryGovParamDeposit() - f.QueryGovParamVoting() - f.QueryGovParamTallying() - - fooAddr := f.KeyAddress(keyFoo) - - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - proposalsQuery := f.QueryGovProposals() - require.Empty(t, proposalsQuery) - - // Test submit generate only for submit proposal - proposalTokens := sdk.TokensFromConsensusPower(5) - success, stdout, stderr := f.TxGovSubmitProposal( - fooAddr.String(), "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "--generate-only", "-y") - require.True(t, success) - require.Empty(t, stderr) - msg := unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test --dry-run - success, _, _ = f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "--dry-run") - require.True(t, success) - - // Create the proposal - f.TxGovSubmitProposal(keyFoo, "Text", "Test", "test", sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure transaction events can be queried - searchResult := f.QueryTxs(1, 50, "message.action=submit_proposal", fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure deposit was deducted - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens), fooAcc.GetCoins().AmountOf(denom)) - - // Ensure propsal is directly queryable - proposal1 := f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - - // Ensure query proposals returns properly - proposalsQuery = f.QueryGovProposals() - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // Query the deposits on the proposal - deposit := f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) - - // Test deposit generate only - depositTokens := sdk.TokensFromConsensusPower(10) - success, stdout, stderr = f.TxGovDeposit(1, fooAddr.String(), sdk.NewCoin(denom, depositTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Run the deposit transaction - f.TxGovDeposit(1, keyFoo, sdk.NewCoin(denom, depositTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // test query deposit - deposits := f.QueryGovDeposits(1) - require.Len(t, deposits, 1) - require.Equal(t, proposalTokens.Add(depositTokens), deposits[0].Amount.AmountOf(denom)) - - // Ensure querying the deposit returns the proper amount - deposit = f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens.Add(depositTokens), deposit.Amount.AmountOf(denom)) - - // Ensure events are set on the transaction - searchResult = f.QueryTxs(1, 50, "message.action=deposit", fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure account has expected amount of funds - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens.Add(depositTokens)), fooAcc.GetCoins().AmountOf(denom)) - - // Fetch the proposal and ensure it is now in the voting period - proposal1 = f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusVotingPeriod, proposal1.Status) - - // Test vote generate only - success, stdout, stderr = f.TxGovVote(1, gov.OptionYes, fooAddr.String(), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.NotZero(t, msg.Fee.Gas) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Vote on the proposal - f.TxGovVote(1, gov.OptionYes, keyFoo, "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Query the vote - vote := f.QueryGovVote(1, fooAddr) - require.Equal(t, uint64(1), vote.ProposalID) - require.Equal(t, gov.OptionYes, vote.Option) - - // Query the votes - votes := f.QueryGovVotes(1) - require.Len(t, votes, 1) - require.Equal(t, uint64(1), votes[0].ProposalID) - require.Equal(t, gov.OptionYes, votes[0].Option) - - // Ensure events are applied to voting transaction properly - searchResult = f.QueryTxs(1, 50, "message.action=vote", fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, searchResult.Txs, 1) - - // Ensure no proposals in deposit period - proposalsQuery = f.QueryGovProposals("--status=DepositPeriod") - require.Empty(t, proposalsQuery) - - // Ensure the proposal returns as in the voting period - proposalsQuery = f.QueryGovProposals("--status=VotingPeriod") - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // submit a second test proposal - f.TxGovSubmitProposal(keyFoo, "Text", "Apples", "test", sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // Test limit on proposals query - proposalsQuery = f.QueryGovProposals("--limit=2") - require.Len(t, proposalsQuery, 2) - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - f.Cleanup() -} - -func TestGaiaCLISubmitParamChangeProposal(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // write proposal to file - proposalTokens := sdk.TokensFromConsensusPower(5) - proposal := fmt.Sprintf(`{ - "title": "Param Change", - "description": "Update max validators", - "changes": [ - { - "subspace": "staking", - "key": "MaxValidators", - "value": 105 - } - ], - "deposit": [ - { - "denom": "stake", - "amount": "%s" - } - ] -} -`, proposalTokens.String()) - - proposalFile := WriteToNewTempFile(t, proposal) - - // create the param change proposal - f.TxGovSubmitParamChangeProposal(keyFoo, proposalFile.Name(), sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure transaction events can be queried - txsPage := f.QueryTxs(1, 50, "message.action=submit_proposal", fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage.Txs, 1) - - // ensure deposit was deducted - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens).String(), fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom).String()) - - // ensure proposal is directly queryable - proposal1 := f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - - // ensure correct query proposals result - proposalsQuery := f.QueryGovProposals() - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // ensure the correct deposit amount on the proposal - deposit := f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLISubmitCommunityPoolSpendProposal(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // create some inflation - cdc := app.MakeCodec() - genesisState := f.GenesisState() - inflationMin := sdk.MustNewDecFromStr("1.0") - var mintData mint.GenesisState - cdc.UnmarshalJSON(genesisState[mint.ModuleName], &mintData) - mintData.Minter.Inflation = inflationMin - mintData.Params.InflationMin = inflationMin - mintData.Params.InflationMax = sdk.MustNewDecFromStr("1.0") - mintDataBz, err := cdc.MarshalJSON(mintData) - require.NoError(t, err) - genesisState[mint.ModuleName] = mintDataBz - - genFile := filepath.Join(f.GaiadHome, "config", "genesis.json") - genDoc, err := tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - genDoc.AppState, err = cdc.MarshalJSON(genesisState) - require.NoError(t, genDoc.SaveAs(genFile)) - - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - tests.WaitForNextNBlocksTM(3, f.Port) - - // write proposal to file - proposalTokens := sdk.TokensFromConsensusPower(5) - proposal := fmt.Sprintf(`{ - "title": "Community Pool Spend", - "description": "Spend from community pool", - "recipient": "%s", - "amount": [ - { - "denom": "%s", - "amount": "1" - } - ], - "deposit": [ - { - "denom": "%s", - "amount": "%s" - } - ] -} -`, fooAddr, sdk.DefaultBondDenom, sdk.DefaultBondDenom, proposalTokens.String()) - proposalFile := WriteToNewTempFile(t, proposal) - - // create the param change proposal - f.TxGovSubmitCommunityPoolSpendProposal(keyFoo, proposalFile.Name(), sdk.NewCoin(denom, proposalTokens), "-y") - tests.WaitForNextNBlocksTM(1, f.Port) - - // ensure transaction events can be queried - txsPage := f.QueryTxs(1, 50, "message.action=submit_proposal", fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage.Txs, 1) - - // ensure deposit was deducted - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, startTokens.Sub(proposalTokens).String(), fooAcc.GetCoins().AmountOf(sdk.DefaultBondDenom).String()) - - // ensure proposal is directly queryable - proposal1 := f.QueryGovProposal(1) - require.Equal(t, uint64(1), proposal1.ProposalID) - require.Equal(t, gov.StatusDepositPeriod, proposal1.Status) - - // ensure correct query proposals result - proposalsQuery := f.QueryGovProposals() - require.Equal(t, uint64(1), proposalsQuery[0].ProposalID) - - // ensure the correct deposit amount on the proposal - deposit := f.QueryGovDeposit(1, fooAddr) - require.Equal(t, proposalTokens, deposit.Amount.AmountOf(denom)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIQueryTxPagination(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - accFoo := f.QueryAccount(fooAddr) - seq := accFoo.GetSequence() - - for i := 1; i <= 30; i++ { - success, _, _ := f.TxSend(keyFoo, barAddr, sdk.NewInt64Coin(fooDenom, int64(i)), fmt.Sprintf("--sequence=%d", seq), "-y") - require.True(t, success) - seq++ - } - - // perPage = 15, 2 pages - txsPage1 := f.QueryTxs(1, 15, fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage1.Txs, 15) - require.Equal(t, txsPage1.Count, 15) - txsPage2 := f.QueryTxs(2, 15, fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage2.Txs, 15) - require.NotEqual(t, txsPage1.Txs, txsPage2.Txs) - - // perPage = 16, 2 pages - txsPage1 = f.QueryTxs(1, 16, fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage1.Txs, 16) - txsPage2 = f.QueryTxs(2, 16, fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPage2.Txs, 14) - require.NotEqual(t, txsPage1.Txs, txsPage2.Txs) - - // perPage = 50 - txsPageFull := f.QueryTxs(1, 50, fmt.Sprintf("message.sender=%s", fooAddr)) - require.Len(t, txsPageFull.Txs, 30) - require.Equal(t, txsPageFull.Txs, append(txsPage1.Txs, txsPage2.Txs...)) - - // perPage = 0 - f.QueryTxsInvalid(errors.New("ERROR: page must greater than 0"), 0, 50, fmt.Sprintf("message.sender=%s", fooAddr)) - - // limit = 0 - f.QueryTxsInvalid(errors.New("ERROR: limit must greater than 0"), 1, 0, fmt.Sprintf("message.sender=%s", fooAddr)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIValidateSignatures(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - // generate sendTx with default gas - success, stdout, stderr := f.TxSend(fooAddr.String(), barAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - - // write unsigned tx to file - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // validate we can successfully sign - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name()) - require.True(t, success) - stdTx := unmarshalStdTx(t, stdout) - require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, 1, len(stdTx.GetSignatures())) - require.Equal(t, fooAddr.String(), stdTx.GetSigners()[0].String()) - - // write signed tx to file - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // validate signatures - success, _, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - - // modify the transaction - stdTx.Memo = "MODIFIED-ORIGINAL-TX-BAD" - bz := marshalStdTx(t, stdTx) - modSignedTxFile := WriteToNewTempFile(t, string(bz)) - defer os.Remove(modSignedTxFile.Name()) - - // validate signature validation failure due to different transaction sig bytes - success, _, _ = f.TxSign(keyFoo, modSignedTxFile.Name(), "--validate-signatures") - require.False(t, success) - - f.Cleanup() -} - -func TestGaiaCLISendGenerateSignAndBroadcast(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - fooAddr := f.KeyAddress(keyFoo) - barAddr := f.KeyAddress(keyBar) - - // Test generate sendTx with default gas - sendTokens := sdk.TokensFromConsensusPower(10) - success, stdout, stderr := f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg := unmarshalStdTx(t, stdout) - require.Equal(t, msg.Fee.Gas, uint64(flags.DefaultGasLimit)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx with --gas=$amount - success, stdout, stderr = f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--gas=100", "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.Equal(t, msg.Fee.Gas, uint64(100)) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 0, len(msg.GetSignatures())) - - // Test generate sendTx, estimate gas - success, stdout, stderr = f.TxSend(fooAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - msg = unmarshalStdTx(t, stdout) - require.True(t, msg.Fee.Gas > 0) - require.Equal(t, len(msg.Msgs), 1) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Test sign --validate-signatures - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--validate-signatures") - require.False(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n\n", fooAddr.String()), stdout) - - // Test sign - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name()) - require.True(t, success) - msg = unmarshalStdTx(t, stdout) - require.Equal(t, len(msg.Msgs), 1) - require.Equal(t, 1, len(msg.GetSignatures())) - require.Equal(t, fooAddr.String(), msg.GetSigners()[0].String()) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Test sign --validate-signatures - success, stdout, _ = f.TxSign(keyFoo, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - require.Equal(t, fmt.Sprintf("Signers:\n 0: %v\n\nSignatures:\n 0: %v\t\t\t[OK]\n\n", fooAddr.String(), - fooAddr.String()), stdout) - - // Ensure foo has right amount of funds - fooAcc := f.QueryAccount(fooAddr) - startTokens := sdk.TokensFromConsensusPower(50) - require.Equal(t, startTokens, fooAcc.GetCoins().AmountOf(denom)) - - // Test broadcast - success, stdout, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account state - barAcc := f.QueryAccount(barAddr) - fooAcc = f.QueryAccount(fooAddr) - require.Equal(t, sendTokens, barAcc.GetCoins().AmountOf(denom)) - require.Equal(t, startTokens.Sub(sendTokens), fooAcc.GetCoins().AmountOf(denom)) - - f.Cleanup() -} - -func TestGaiaCLIMultisignInsufficientCosigners(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - barAddr := f.KeyAddress(keyBar) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Test generate sendTx with multisig - success, stdout, _ := f.TxSend(fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(denom, 5), "--generate-only") - require.True(t, success) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Multisign, not enough signatures - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{fooSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures") - require.False(t, success) - - // Broadcast the transaction - success, stdOut, _ := f.TxBroadcast(signedTxFile.Name()) - require.Contains(t, stdOut, "signature verification failed") - require.True(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIEncode(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - cdc := app.MakeCodec() - - // Build a testing transaction and write it to disk - barAddr := f.KeyAddress(keyBar) - keyAddr := f.KeyAddress(keyFoo) - - sendTokens := sdk.TokensFromConsensusPower(10) - success, stdout, stderr := f.TxSend(keyAddr.String(), barAddr, sdk.NewCoin(denom, sendTokens), "--generate-only", "--memo", "deadbeef") - require.True(t, success) - require.Empty(t, stderr) - - // Write it to disk - jsonTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(jsonTxFile.Name()) - - // Run the encode command, and trim the extras from the stdout capture - success, base64Encoded, _ := f.TxEncode(jsonTxFile.Name()) - require.True(t, success) - trimmedBase64 := strings.Trim(base64Encoded, "\"\n") - - // Decode the base64 - decodedBytes, err := base64.StdEncoding.DecodeString(trimmedBase64) - require.Nil(t, err) - - // Check that the transaction decodes as epxceted - var decodedTx auth.StdTx - require.Nil(t, cdc.UnmarshalBinaryLengthPrefixed(decodedBytes, &decodedTx)) - require.Equal(t, "deadbeef", decodedTx.Memo) -} - -func TestGaiaCLIMultisignSortSignatures(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - barAddr := f.KeyAddress(keyBar) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - fooBarBazAcc := f.QueryAccount(fooBarBazAddr) - require.Equal(t, int64(10), fooBarBazAcc.GetCoins().AmountOf(denom).Int64()) - - // Test generate sendTx with multisig - success, stdout, _ := f.TxSend(fooBarBazAddr.String(), barAddr, sdk.NewInt64Coin(denom, 5), "--generate-only") - require.True(t, success) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Sign with baz's key - success, stdout, _ = f.TxSign(keyBaz, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String()) - require.True(t, success) - - // Write the output to disk - bazSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(bazSignatureFile.Name()) - - // Multisign, keys in different order - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{ - bazSignatureFile.Name(), fooSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures") - require.True(t, success) - - // Broadcast the transaction - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIMultisign(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server with minimum fees - proc := f.GDStart() - defer proc.Stop(false) - - fooBarBazAddr := f.KeyAddress(keyFooBarBaz) - bazAddr := f.KeyAddress(keyBaz) - - // Send some tokens from one account to the other - success, _, _ := f.TxSend(keyFoo, fooBarBazAddr, sdk.NewInt64Coin(denom, 10), "-y") - require.True(t, success) - tests.WaitForNextNBlocksTM(1, f.Port) - - // Ensure account balances match expected - fooBarBazAcc := f.QueryAccount(fooBarBazAddr) - require.Equal(t, int64(10), fooBarBazAcc.GetCoins().AmountOf(denom).Int64()) - - // Test generate sendTx with multisig - success, stdout, stderr := f.TxSend(fooBarBazAddr.String(), bazAddr, sdk.NewInt64Coin(denom, 10), "--generate-only") - require.True(t, success) - require.Empty(t, stderr) - - // Write the output to disk - unsignedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(unsignedTxFile.Name()) - - // Sign with foo's key - success, stdout, _ = f.TxSign(keyFoo, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - fooSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(fooSignatureFile.Name()) - - // Sign with bar's key - success, stdout, _ = f.TxSign(keyBar, unsignedTxFile.Name(), "--multisig", fooBarBazAddr.String(), "-y") - require.True(t, success) - - // Write the output to disk - barSignatureFile := WriteToNewTempFile(t, stdout) - defer os.Remove(barSignatureFile.Name()) - - // Multisign - success, stdout, _ = f.TxMultisign(unsignedTxFile.Name(), keyFooBarBaz, []string{ - fooSignatureFile.Name(), barSignatureFile.Name()}) - require.True(t, success) - - // Write the output to disk - signedTxFile := WriteToNewTempFile(t, stdout) - defer os.Remove(signedTxFile.Name()) - - // Validate the multisignature - success, _, _ = f.TxSign(keyFooBarBaz, signedTxFile.Name(), "--validate-signatures", "-y") - require.True(t, success) - - // Broadcast the transaction - success, _, _ = f.TxBroadcast(signedTxFile.Name()) - require.True(t, success) - - // Cleanup testing directories - f.Cleanup() -} - -func TestGaiaCLIConfig(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - node := fmt.Sprintf("%s:%s", f.RPCAddr, f.Port) - - // Set available configuration options - f.CLIConfig("broadcast-mode", "block") - f.CLIConfig("node", node) - f.CLIConfig("output", "text") - f.CLIConfig("trust-node", "true") - f.CLIConfig("chain-id", f.ChainID) - f.CLIConfig("trace", "false") - f.CLIConfig("indent", "true") - f.CLIConfig("keyring-backend", "test") - - config, err := ioutil.ReadFile(path.Join(f.GaiacliHome, "config", "config.toml")) - require.NoError(t, err) - expectedConfig := fmt.Sprintf(`broadcast-mode = "block" -chain-id = "%s" -indent = true -keyring-backend = "test" -node = "%s" -output = "text" -trace = false -trust-node = true -`, f.ChainID, node) - require.Equal(t, expectedConfig, string(config)) - - f.Cleanup() -} - -func TestGaiadCollectGentxs(t *testing.T) { - t.Parallel() - var customMaxBytes, customMaxGas int64 = 99999999, 1234567 - f := NewFixtures(t) - - // Initialise temporary directories - gentxDir, err := ioutil.TempDir("", "") - gentxDoc := filepath.Join(gentxDir, "gentx.json") - require.NoError(t, err) - - // Reset testing path - f.UnsafeResetAll() - - // Initialize keys - f.KeysAdd(keyFoo) - - // Configure json output - f.CLIConfig("output", "json") - - // Run init - f.GDInit(keyFoo) - - // Customise genesis.json - - genFile := f.GenesisFile() - genDoc, err := tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - genDoc.ConsensusParams.Block.MaxBytes = customMaxBytes - genDoc.ConsensusParams.Block.MaxGas = customMaxGas - genDoc.SaveAs(genFile) - - // Add account to genesis.json - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - - // Write gentx file - f.GenTx(keyFoo, fmt.Sprintf("--output-document=%s", gentxDoc)) - - // Collect gentxs from a custom directory - f.CollectGenTxs(fmt.Sprintf("--gentx-dir=%s", gentxDir)) - - genDoc, err = tmtypes.GenesisDocFromFile(genFile) - require.NoError(t, err) - require.Equal(t, genDoc.ConsensusParams.Block.MaxBytes, customMaxBytes) - require.Equal(t, genDoc.ConsensusParams.Block.MaxGas, customMaxGas) - - f.Cleanup(gentxDir) -} - -func TestGaiadAddGenesisAccount(t *testing.T) { - t.Parallel() - f := NewFixtures(t) - - // Reset testing path - f.UnsafeResetAll() - - // Initialize keys - f.KeysDelete(keyFoo) - f.KeysDelete(keyBar) - f.KeysDelete(keyBaz) - f.KeysAdd(keyFoo) - f.KeysAdd(keyBar) - f.KeysAdd(keyBaz) - - // Configure json output - f.CLIConfig("output", "json") - - // Run init - f.GDInit(keyFoo) - - // Add account to genesis.json - bazCoins := sdk.Coins{ - sdk.NewInt64Coin("acoin", 1000000), - sdk.NewInt64Coin("bcoin", 1000000), - } - - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - f.AddGenesisAccount(f.KeyAddress(keyBar), bazCoins) - genesisState := f.GenesisState() - - cdc := app.MakeCodec() - accounts := auth.GetGenesisStateFromAppState(cdc, genesisState).Accounts - - require.Equal(t, accounts[0].GetAddress(), f.KeyAddress(keyFoo)) - require.Equal(t, accounts[1].GetAddress(), f.KeyAddress(keyBar)) - require.True(t, accounts[0].GetCoins().IsEqual(startCoins)) - require.True(t, accounts[1].GetCoins().IsEqual(bazCoins)) - - // Cleanup testing directories - f.Cleanup() -} - -func TestSlashingGetParams(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - params := f.QuerySlashingParams() - require.Equal(t, int64(100), params.SignedBlocksWindow) - require.Equal(t, sdk.NewDecWithPrec(5, 1), params.MinSignedPerWindow) - - sinfo := f.QuerySigningInfo(f.GDTendermint("show-validator")) - require.Equal(t, int64(0), sinfo.StartHeight) - require.False(t, sinfo.Tombstoned) - - // Cleanup testing directories - f.Cleanup() -} - -func TestValidateGenesis(t *testing.T) { - t.Parallel() - f := InitFixtures(t) - - // start wasmd server - proc := f.GDStart() - defer proc.Stop(false) - - f.ValidateGenesis() - - // Cleanup testing directories - f.Cleanup() -} diff --git a/cli_test/doc.go b/cli_test/doc.go deleted file mode 100644 index bcf9c5e4d0..0000000000 --- a/cli_test/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -package clitest - -// package clitest runs integration tests which make use of CLI commands. diff --git a/cli_test/test_helpers.go b/cli_test/test_helpers.go deleted file mode 100644 index d19bc23fa8..0000000000 --- a/cli_test/test_helpers.go +++ /dev/null @@ -1,785 +0,0 @@ -package clitest - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "testing" - "time" - - "github.com/stretchr/testify/require" - tmtypes "github.com/tendermint/tendermint/types" - - "github.com/CosmWasm/wasmd/app" - - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/simapp" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/slashing" - "github.com/cosmos/cosmos-sdk/x/staking" -) - -const ( - denom = "stake" - keyFoo = "foo" - keyBar = "bar" - fooDenom = "footoken" - feeDenom = "feetoken" - fee2Denom = "fee2token" - keyBaz = "baz" - keyVesting = "vesting" - keyFooBarBaz = "foobarbaz" -) - -var ( - // nolint:varcheck,deadcode,unused - totalCoins = sdk.NewCoins( - sdk.NewCoin(fee2Denom, sdk.TokensFromConsensusPower(2000000)), - sdk.NewCoin(feeDenom, sdk.TokensFromConsensusPower(2000000)), - sdk.NewCoin(fooDenom, sdk.TokensFromConsensusPower(2000)), - sdk.NewCoin(denom, sdk.TokensFromConsensusPower(300).Add(sdk.NewInt(12))), // add coins from inflation - ) - - startCoins = sdk.NewCoins( - sdk.NewCoin(fee2Denom, sdk.TokensFromConsensusPower(1000000)), - sdk.NewCoin(feeDenom, sdk.TokensFromConsensusPower(1000000)), - sdk.NewCoin(fooDenom, sdk.TokensFromConsensusPower(1000)), - sdk.NewCoin(denom, sdk.TokensFromConsensusPower(150)), - ) - - vestingCoins = sdk.NewCoins( - sdk.NewCoin(feeDenom, sdk.TokensFromConsensusPower(500000)), - ) -) - -//___________________________________________________________________________________ -// Fixtures - -// Fixtures is used to setup the testing environment -type Fixtures struct { - BuildDir string - RootDir string - GaiadBinary string - GaiacliBinary string - ChainID string - RPCAddr string - Port string - GaiadHome string - GaiacliHome string - P2PAddr string - T *testing.T -} - -// NewFixtures creates a new instance of Fixtures with many vars set -func NewFixtures(t *testing.T) *Fixtures { - tmpDir, err := ioutil.TempDir("", "gaia_integration_"+t.Name()+"_") - require.NoError(t, err) - - servAddr, port, err := server.FreeTCPAddr() - require.NoError(t, err) - - p2pAddr, _, err := server.FreeTCPAddr() - require.NoError(t, err) - - buildDir := os.Getenv("BUILDDIR") - if buildDir == "" { - buildDir, err = filepath.Abs("../build/") - require.NoError(t, err) - } - - return &Fixtures{ - T: t, - BuildDir: buildDir, - RootDir: tmpDir, - GaiadBinary: filepath.Join(buildDir, "wasmd"), - GaiacliBinary: filepath.Join(buildDir, "wasmcli"), - GaiadHome: filepath.Join(tmpDir, ".wasmd"), - GaiacliHome: filepath.Join(tmpDir, ".wasmcli"), - RPCAddr: servAddr, - P2PAddr: p2pAddr, - Port: port, - } -} - -// GenesisFile returns the path of the genesis file -func (f Fixtures) GenesisFile() string { - return filepath.Join(f.GaiadHome, "config", "genesis.json") -} - -// GenesisFile returns the application's genesis state -func (f Fixtures) GenesisState() simapp.GenesisState { - cdc := codec.New() - genDoc, err := tmtypes.GenesisDocFromFile(f.GenesisFile()) - require.NoError(f.T, err) - - var appState simapp.GenesisState - require.NoError(f.T, cdc.UnmarshalJSON(genDoc.AppState, &appState)) - return appState -} - -// InitFixtures is called at the beginning of a test and initializes a chain -// with 1 validator. -func InitFixtures(t *testing.T) (f *Fixtures) { - f = NewFixtures(t) - - // reset test state - f.UnsafeResetAll() - - f.CLIConfig("keyring-backend", "test") - - // ensure keystore has foo and bar keys - f.KeysDelete(keyFoo) - f.KeysDelete(keyBar) - f.KeysDelete(keyBar) - f.KeysDelete(keyFooBarBaz) - f.KeysAdd(keyFoo) - f.KeysAdd(keyBar) - f.KeysAdd(keyBaz) - f.KeysAdd(keyVesting) - f.KeysAdd(keyFooBarBaz, "--multisig-threshold=2", fmt.Sprintf( - "--multisig=%s,%s,%s", keyFoo, keyBar, keyBaz)) - - // ensure that CLI output is in JSON format - f.CLIConfig("output", "json") - - // NOTE: GDInit sets the ChainID - f.GDInit(keyFoo) - - f.CLIConfig("chain-id", f.ChainID) - f.CLIConfig("broadcast-mode", "block") - f.CLIConfig("trust-node", "true") - - // start an account with tokens - f.AddGenesisAccount(f.KeyAddress(keyFoo), startCoins) - f.AddGenesisAccount( - f.KeyAddress(keyVesting), startCoins, - fmt.Sprintf("--vesting-amount=%s", vestingCoins), - fmt.Sprintf("--vesting-start-time=%d", time.Now().UTC().UnixNano()), - fmt.Sprintf("--vesting-end-time=%d", time.Now().Add(60*time.Second).UTC().UnixNano()), - ) - - f.GenTx(keyFoo) - f.CollectGenTxs() - - return f -} - -// Cleanup is meant to be run at the end of a test to clean up an remaining test state -func (f *Fixtures) Cleanup(dirs ...string) { - clean := append(dirs, f.RootDir) - for _, d := range clean { - require.NoError(f.T, os.RemoveAll(d)) - } -} - -// Flags returns the flags necessary for making most CLI calls -func (f *Fixtures) Flags() string { - return fmt.Sprintf("--home=%s --node=%s", f.GaiacliHome, f.RPCAddr) -} - -//___________________________________________________________________________________ -// wasmd - -// UnsafeResetAll is wasmd unsafe-reset-all -func (f *Fixtures) UnsafeResetAll(flags ...string) { - cmd := fmt.Sprintf("%s --home=%s unsafe-reset-all", f.GaiadBinary, f.GaiadHome) - executeWrite(f.T, addFlags(cmd, flags)) - err := os.RemoveAll(filepath.Join(f.GaiadHome, "config", "gentx")) - require.NoError(f.T, err) -} - -// GDInit is wasmd init -// NOTE: GDInit sets the ChainID for the Fixtures instance -func (f *Fixtures) GDInit(moniker string, flags ...string) { - cmd := fmt.Sprintf("%s init -o --home=%s %s", f.GaiadBinary, f.GaiadHome, moniker) - _, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) - - var chainID string - var initRes map[string]json.RawMessage - - err := json.Unmarshal([]byte(stderr), &initRes) - require.NoError(f.T, err) - - err = json.Unmarshal(initRes["chain_id"], &chainID) - require.NoError(f.T, err) - - f.ChainID = chainID -} - -// AddGenesisAccount is wasmd add-genesis-account -func (f *Fixtures) AddGenesisAccount(address sdk.AccAddress, coins sdk.Coins, flags ...string) { - cmd := fmt.Sprintf("%s add-genesis-account %s %s --home=%s --keyring-backend=test", f.GaiadBinary, address, coins, f.GaiadHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -// GenTx is wasmd gentx -func (f *Fixtures) GenTx(name string, flags ...string) { - cmd := fmt.Sprintf("%s gentx --name=%s --home=%s --home-client=%s --keyring-backend=test", f.GaiadBinary, name, f.GaiadHome, f.GaiacliHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -// CollectGenTxs is wasmd collect-gentxs -func (f *Fixtures) CollectGenTxs(flags ...string) { - cmd := fmt.Sprintf("%s collect-gentxs --home=%s", f.GaiadBinary, f.GaiadHome) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -// GDStart runs wasmd start with the appropriate flags and returns a process -func (f *Fixtures) GDStart(flags ...string) *tests.Process { - cmd := fmt.Sprintf("%s start --home=%s --rpc.laddr=%v --p2p.laddr=%v", f.GaiadBinary, f.GaiadHome, f.RPCAddr, f.P2PAddr) - proc := tests.GoExecuteTWithStdout(f.T, addFlags(cmd, flags)) - tests.WaitForTMStart(f.Port) - tests.WaitForNextNBlocksTM(1, f.Port) - return proc -} - -// GDTendermint returns the results of wasmd tendermint [query] -func (f *Fixtures) GDTendermint(query string) string { - cmd := fmt.Sprintf("%s tendermint %s --home=%s", f.GaiadBinary, query, f.GaiadHome) - success, stdout, stderr := executeWriteRetStdStreams(f.T, cmd) - require.Empty(f.T, stderr) - require.True(f.T, success) - return strings.TrimSpace(stdout) -} - -// ValidateGenesis runs wasmd validate-genesis -func (f *Fixtures) ValidateGenesis() { - cmd := fmt.Sprintf("%s validate-genesis --home=%s", f.GaiadBinary, f.GaiadHome) - executeWriteCheckErr(f.T, cmd) -} - -//___________________________________________________________________________________ -// wasmcli keys - -// KeysDelete is wasmcli keys delete -func (f *Fixtures) KeysDelete(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys delete --keyring-backend=test --home=%s %s", f.GaiacliBinary, - f.GaiacliHome, name) - executeWrite(f.T, addFlags(cmd, append(append(flags, "-y"), "-f"))) -} - -// KeysAdd is wasmcli keys add -func (f *Fixtures) KeysAdd(name string, flags ...string) { - cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s %s", f.GaiacliBinary, - f.GaiacliHome, name) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -// KeysAddRecover prepares wasmcli keys add --recover -func (f *Fixtures) KeysAddRecover(name, mnemonic string, flags ...string) (exitSuccess bool, stdout, stderr string) { - cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s --recover %s", - f.GaiacliBinary, f.GaiacliHome, name) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), mnemonic) -} - -// KeysAddRecoverHDPath prepares wasmcli keys add --recover --account --index -func (f *Fixtures) KeysAddRecoverHDPath(name, mnemonic string, account uint32, index uint32, flags ...string) { - cmd := fmt.Sprintf("%s keys add --keyring-backend=test --home=%s --recover %s --account %d"+ - " --index %d", f.GaiacliBinary, f.GaiacliHome, name, account, index) - executeWriteCheckErr(f.T, addFlags(cmd, flags), mnemonic) -} - -// KeysShow is wasmcli keys show -func (f *Fixtures) KeysShow(name string, flags ...string) keys.KeyOutput { - cmd := fmt.Sprintf("%s keys show --keyring-backend=test --home=%s %s", f.GaiacliBinary, - f.GaiacliHome, name) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var ko keys.KeyOutput - err := clientkeys.UnmarshalJSON([]byte(out), &ko) - require.NoError(f.T, err) - return ko -} - -// KeyAddress returns the SDK account address from the key -func (f *Fixtures) KeyAddress(name string) sdk.AccAddress { - ko := f.KeysShow(name) - accAddr, err := sdk.AccAddressFromBech32(ko.Address) - require.NoError(f.T, err) - return accAddr -} - -//___________________________________________________________________________________ -// wasmcli config - -// CLIConfig is wasmcli config -func (f *Fixtures) CLIConfig(key, value string, flags ...string) { - cmd := fmt.Sprintf("%s config --home=%s %s %s", f.GaiacliBinary, f.GaiacliHome, key, value) - executeWriteCheckErr(f.T, addFlags(cmd, flags)) -} - -//___________________________________________________________________________________ -// wasmcli tx send/sign/broadcast - -// TxSend is wasmcli tx send -func (f *Fixtures) TxSend(from string, to sdk.AccAddress, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx send --keyring-backend=test %s %s %s %v", f.GaiacliBinary, from, - to, amount, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxSign is wasmcli tx sign -func (f *Fixtures) TxSign(signer, fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx sign %v --keyring-backend=test --from=%s %v", f.GaiacliBinary, - f.Flags(), signer, fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxBroadcast is wasmcli tx broadcast -func (f *Fixtures) TxBroadcast(fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx broadcast %v %v", f.GaiacliBinary, f.Flags(), fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxEncode is wasmcli tx encode -func (f *Fixtures) TxEncode(fileName string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx encode %v %v", f.GaiacliBinary, f.Flags(), fileName) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxMultisign is wasmcli tx multisign -func (f *Fixtures) TxMultisign(fileName, name string, signaturesFiles []string, - flags ...string) (bool, string, string) { - - cmd := fmt.Sprintf("%s tx multisign --keyring-backend=test %v %s %s %s", f.GaiacliBinary, f.Flags(), - fileName, name, strings.Join(signaturesFiles, " "), - ) - return executeWriteRetStdStreams(f.T, cmd) -} - -//___________________________________________________________________________________ -// wasmcli tx staking - -// TxStakingCreateValidator is wasmcli tx staking create-validator -func (f *Fixtures) TxStakingCreateValidator(from, consPubKey string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx staking create-validator %v --keyring-backend=test --from=%s"+ - " --pubkey=%s", f.GaiacliBinary, f.Flags(), from, consPubKey) - cmd += fmt.Sprintf(" --amount=%v --moniker=%v --commission-rate=%v", amount, from, "0.05") - cmd += fmt.Sprintf(" --commission-max-rate=%v --commission-max-change-rate=%v", "0.20", "0.10") - cmd += fmt.Sprintf(" --min-self-delegation=%v", "1") - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxStakingUnbond is wasmcli tx staking unbond -func (f *Fixtures) TxStakingUnbond(from, shares string, validator sdk.ValAddress, flags ...string) bool { - cmd := fmt.Sprintf("%s tx staking unbond --keyring-backend=test %s %v --from=%s %v", - f.GaiacliBinary, validator, shares, from, f.Flags()) - return executeWrite(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -//___________________________________________________________________________________ -// wasmcli tx gov - -// TxGovSubmitProposal is wasmcli tx gov submit-proposal -func (f *Fixtures) TxGovSubmitProposal(from, typ, title, description string, deposit sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov submit-proposal %v --keyring-backend=test --from=%s --type=%s", - f.GaiacliBinary, f.Flags(), from, typ) - cmd += fmt.Sprintf(" --title=%s --description=%s --deposit=%s", title, description, deposit) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxGovDeposit is wasmcli tx gov deposit -func (f *Fixtures) TxGovDeposit(proposalID int, from string, amount sdk.Coin, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov deposit %d %s --keyring-backend=test --from=%s %v", - f.GaiacliBinary, proposalID, amount, from, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxGovVote is wasmcli tx gov vote -func (f *Fixtures) TxGovVote(proposalID int, option gov.VoteOption, from string, flags ...string) (bool, string, string) { - cmd := fmt.Sprintf("%s tx gov vote %d %s --keyring-backend=test --from=%s %v", - f.GaiacliBinary, proposalID, option, from, f.Flags()) - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxGovSubmitParamChangeProposal executes a CLI parameter change proposal -// submission. -func (f *Fixtures) TxGovSubmitParamChangeProposal( - from, proposalPath string, deposit sdk.Coin, flags ...string, -) (bool, string, string) { - - cmd := fmt.Sprintf( - "%s tx gov submit-proposal param-change %s --keyring-backend=test --from=%s %v", - f.GaiacliBinary, proposalPath, from, f.Flags(), - ) - - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -// TxGovSubmitCommunityPoolSpendProposal executes a CLI community pool spend proposal -// submission. -func (f *Fixtures) TxGovSubmitCommunityPoolSpendProposal( - from, proposalPath string, deposit sdk.Coin, flags ...string, -) (bool, string, string) { - - cmd := fmt.Sprintf( - "%s tx gov submit-proposal community-pool-spend %s --keyring-backend=test --from=%s %v", - f.GaiacliBinary, proposalPath, from, f.Flags(), - ) - - return executeWriteRetStdStreams(f.T, addFlags(cmd, flags), clientkeys.DefaultKeyPass) -} - -//___________________________________________________________________________________ -// wasmcli query account - -// QueryAccount is wasmcli query account -func (f *Fixtures) QueryAccount(address sdk.AccAddress, flags ...string) auth.BaseAccount { - cmd := fmt.Sprintf("%s query account %s %v", f.GaiacliBinary, address, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var initRes map[string]json.RawMessage - err := json.Unmarshal([]byte(out), &initRes) - require.NoError(f.T, err, "out %v, err %v", out, err) - value := initRes["value"] - var acc auth.BaseAccount - cdc := codec.New() - codec.RegisterCrypto(cdc) - err = cdc.UnmarshalJSON(value, &acc) - require.NoError(f.T, err, "value %v, err %v", string(value), err) - return acc -} - -//___________________________________________________________________________________ -// wasmcli query txs - -// QueryTxs is wasmcli query txs -func (f *Fixtures) QueryTxs(page, limit int, events ...string) *sdk.SearchTxsResult { - cmd := fmt.Sprintf("%s query txs --page=%d --limit=%d --events='%s' %v", f.GaiacliBinary, page, limit, queryEvents(events), f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var result sdk.SearchTxsResult - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &result) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return &result -} - -// QueryTxsInvalid query txs with wrong parameters and compare expected error -func (f *Fixtures) QueryTxsInvalid(expectedErr error, page, limit int, events ...string) { - cmd := fmt.Sprintf("%s query txs --page=%d --limit=%d --events='%s' %v", f.GaiacliBinary, page, limit, queryEvents(events), f.Flags()) - _, err := tests.ExecuteT(f.T, cmd, "") - require.EqualError(f.T, expectedErr, err) -} - -//___________________________________________________________________________________ -// wasmcli query staking - -// QueryStakingValidator is wasmcli query staking validator -func (f *Fixtures) QueryStakingValidator(valAddr sdk.ValAddress, flags ...string) staking.Validator { - cmd := fmt.Sprintf("%s query staking validator %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var validator staking.Validator - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &validator) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return validator -} - -// QueryStakingUnbondingDelegationsFrom is wasmcli query staking unbonding-delegations-from -func (f *Fixtures) QueryStakingUnbondingDelegationsFrom(valAddr sdk.ValAddress, flags ...string) []staking.UnbondingDelegation { - cmd := fmt.Sprintf("%s query staking unbonding-delegations-from %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var ubds []staking.UnbondingDelegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &ubds) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return ubds -} - -// QueryStakingDelegationsTo is wasmcli query staking delegations-to -func (f *Fixtures) QueryStakingDelegationsTo(valAddr sdk.ValAddress, flags ...string) []staking.Delegation { - cmd := fmt.Sprintf("%s query staking delegations-to %s %v", f.GaiacliBinary, valAddr, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var delegations []staking.Delegation - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &delegations) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return delegations -} - -// QueryStakingPool is wasmcli query staking pool -func (f *Fixtures) QueryStakingPool(flags ...string) staking.Pool { - cmd := fmt.Sprintf("%s query staking pool %v", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var pool staking.Pool - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &pool) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return pool -} - -// QueryStakingParameters is wasmcli query staking parameters -func (f *Fixtures) QueryStakingParameters(flags ...string) staking.Params { - cmd := fmt.Sprintf("%s query staking params %v", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var params staking.Params - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), ¶ms) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return params -} - -//___________________________________________________________________________________ -// wasmcli query gov - -// QueryGovParamDeposit is wasmcli query gov param deposit -func (f *Fixtures) QueryGovParamDeposit() gov.DepositParams { - cmd := fmt.Sprintf("%s query gov param deposit %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var depositParam gov.DepositParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &depositParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return depositParam -} - -// QueryGovParamVoting is wasmcli query gov param voting -func (f *Fixtures) QueryGovParamVoting() gov.VotingParams { - cmd := fmt.Sprintf("%s query gov param voting %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var votingParam gov.VotingParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votingParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return votingParam -} - -// QueryGovParamTallying is wasmcli query gov param tallying -func (f *Fixtures) QueryGovParamTallying() gov.TallyParams { - cmd := fmt.Sprintf("%s query gov param tallying %s", f.GaiacliBinary, f.Flags()) - out, _ := tests.ExecuteT(f.T, cmd, "") - var tallyingParam gov.TallyParams - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &tallyingParam) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return tallyingParam -} - -// QueryGovProposals is wasmcli query gov proposals -func (f *Fixtures) QueryGovProposals(flags ...string) gov.Proposals { - cmd := fmt.Sprintf("%s query gov proposals %v", f.GaiacliBinary, f.Flags()) - stdout, stderr := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - if strings.Contains(stderr, "no matching proposals found") { - return gov.Proposals{} - } - require.Empty(f.T, stderr) - var out gov.Proposals - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(stdout), &out) - require.NoError(f.T, err) - return out -} - -// QueryGovProposal is wasmcli query gov proposal -func (f *Fixtures) QueryGovProposal(proposalID int, flags ...string) gov.Proposal { - cmd := fmt.Sprintf("%s query gov proposal %d %v", f.GaiacliBinary, proposalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var proposal gov.Proposal - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &proposal) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return proposal -} - -// QueryGovVote is wasmcli query gov vote -func (f *Fixtures) QueryGovVote(proposalID int, voter sdk.AccAddress, flags ...string) gov.Vote { - cmd := fmt.Sprintf("%s query gov vote %d %s %v", f.GaiacliBinary, proposalID, voter, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var vote gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &vote) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return vote -} - -// QueryGovVotes is wasmcli query gov votes -func (f *Fixtures) QueryGovVotes(proposalID int, flags ...string) []gov.Vote { - cmd := fmt.Sprintf("%s query gov votes %d %v", f.GaiacliBinary, proposalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var votes []gov.Vote - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &votes) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return votes -} - -// QueryGovDeposit is wasmcli query gov deposit -func (f *Fixtures) QueryGovDeposit(proposalID int, depositor sdk.AccAddress, flags ...string) gov.Deposit { - cmd := fmt.Sprintf("%s query gov deposit %d %s %v", f.GaiacliBinary, proposalID, depositor, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var deposit gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposit) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return deposit -} - -// QueryGovDeposits is wasmcli query gov deposits -func (f *Fixtures) QueryGovDeposits(propsalID int, flags ...string) []gov.Deposit { - cmd := fmt.Sprintf("%s query gov deposits %d %v", f.GaiacliBinary, propsalID, f.Flags()) - out, _ := tests.ExecuteT(f.T, addFlags(cmd, flags), "") - var deposits []gov.Deposit - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(out), &deposits) - require.NoError(f.T, err, "out %v\n, err %v", out, err) - return deposits -} - -//___________________________________________________________________________________ -// query slashing - -// QuerySigningInfo returns the signing info for a validator -func (f *Fixtures) QuerySigningInfo(val string) slashing.ValidatorSigningInfo { - cmd := fmt.Sprintf("%s query slashing signing-info %s %s", f.GaiacliBinary, val, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var sinfo slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON([]byte(res), &sinfo) - require.NoError(f.T, err) - return sinfo -} - -// QuerySlashingParams is wasmcli query slashing params -func (f *Fixtures) QuerySlashingParams() slashing.Params { - cmd := fmt.Sprintf("%s query slashing params %s", f.GaiacliBinary, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var params slashing.Params - err := cdc.UnmarshalJSON([]byte(res), ¶ms) - require.NoError(f.T, err) - return params -} - -//___________________________________________________________________________________ -// query distribution - -// QueryRewards returns the rewards of a delegator -func (f *Fixtures) QueryRewards(delAddr sdk.AccAddress, flags ...string) distribution.QueryDelegatorTotalRewardsResponse { - cmd := fmt.Sprintf("%s query distribution rewards %s %s", f.GaiacliBinary, delAddr, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var rewards distribution.QueryDelegatorTotalRewardsResponse - err := cdc.UnmarshalJSON([]byte(res), &rewards) - require.NoError(f.T, err) - return rewards -} - -//___________________________________________________________________________________ -// query supply - -// QueryTotalSupply returns the total supply of coins -func (f *Fixtures) QueryTotalSupply(flags ...string) (totalSupply sdk.Coins) { - cmd := fmt.Sprintf("%s query supply total %s", f.GaiacliBinary, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - err := cdc.UnmarshalJSON([]byte(res), &totalSupply) - require.NoError(f.T, err) - return totalSupply -} - -// QueryTotalSupplyOf returns the total supply of a given coin denom -func (f *Fixtures) QueryTotalSupplyOf(denom string, flags ...string) sdk.Int { - cmd := fmt.Sprintf("%s query supply total %s %s", f.GaiacliBinary, denom, f.Flags()) - res, errStr := tests.ExecuteT(f.T, cmd, "") - require.Empty(f.T, errStr) - cdc := app.MakeCodec() - var supplyOf sdk.Int - err := cdc.UnmarshalJSON([]byte(res), &supplyOf) - require.NoError(f.T, err) - return supplyOf -} - -//___________________________________________________________________________________ -// executors - -func executeWriteCheckErr(t *testing.T, cmdStr string, writes ...string) { - require.True(t, executeWrite(t, cmdStr, writes...)) -} - -func executeWrite(t *testing.T, cmdStr string, writes ...string) (exitSuccess bool) { - exitSuccess, _, _ = executeWriteRetStdStreams(t, cmdStr, writes...) - return -} - -func executeWriteRetStdStreams(t *testing.T, cmdStr string, writes ...string) (bool, string, string) { - proc := tests.GoExecuteT(t, cmdStr) - - // Enables use of interactive commands - for _, write := range writes { - _, err := proc.StdinPipe.Write([]byte(write + "\n")) - require.NoError(t, err) - } - - // Read both stdout and stderr from the process - stdout, stderr, err := proc.ReadAll() - if err != nil { - fmt.Println("Err on proc.ReadAll()", err, cmdStr) - } - - // Log output. - if len(stdout) > 0 { - t.Log("Stdout:", string(stdout)) - } - if len(stderr) > 0 { - t.Log("Stderr:", string(stderr)) - } - - // Wait for process to exit - proc.Wait() - - // Return succes, stdout, stderr - return proc.ExitState.Success(), string(stdout), string(stderr) -} - -//___________________________________________________________________________________ -// utils - -func addFlags(cmd string, flags []string) string { - for _, f := range flags { - cmd += " " + f - } - return strings.TrimSpace(cmd) -} - -func queryEvents(events []string) (out string) { - for _, event := range events { - out += event + "&" - } - return strings.TrimSuffix(out, "&") -} - -// Write the given string to a new temporary file -func WriteToNewTempFile(t *testing.T, s string) *os.File { - fp, err := ioutil.TempFile(os.TempDir(), "cosmos_cli_test_") - require.Nil(t, err) - _, err = fp.WriteString(s) - require.Nil(t, err) - return fp -} - -//nolint:deadcode,unused -func marshalStdTx(t *testing.T, stdTx auth.StdTx) []byte { - cdc := app.MakeCodec() - bz, err := cdc.MarshalBinaryBare(stdTx) - require.NoError(t, err) - return bz -} - -//nolint:deadcode,unused -func unmarshalStdTx(t *testing.T, s string) (stdTx auth.StdTx) { - cdc := app.MakeCodec() - require.Nil(t, cdc.UnmarshalJSON([]byte(s), &stdTx)) - return -} diff --git a/cmd/wasmcli/main.go b/cmd/wasmcli/main.go index a4e12a2460..9663b15594 100644 --- a/cmd/wasmcli/main.go +++ b/cmd/wasmcli/main.go @@ -1,39 +1,34 @@ package main import ( + "context" "fmt" "os" - "path" - - "github.com/spf13/cobra" - "github.com/spf13/viper" + "github.com/CosmWasm/wasmd/app" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/lcd" "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" authcmd "github.com/cosmos/cosmos-sdk/x/auth/client/cli" - authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - "github.com/cosmos/cosmos-sdk/x/bank" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + vestingcli "github.com/cosmos/cosmos-sdk/x/auth/vesting/client/cli" bankcmd "github.com/cosmos/cosmos-sdk/x/bank/client/cli" - - "github.com/tendermint/go-amino" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/spf13/cobra" "github.com/tendermint/tendermint/libs/cli" - - "github.com/CosmWasm/wasmd/app" ) +// ClientName is set via build process +const ClientName = "wasmcli" + func main() { // Configure cobra to sort commands cobra.EnableCommandSorting = false - // Instantiate the codec for the command line application - cdc := app.MakeCodec() - // Read in the configuration file for the sdk config := sdk.GetConfig() config.SetBech32PrefixForAccount(app.Bech32PrefixAccAddr, app.Bech32PrefixAccPub) @@ -45,130 +40,125 @@ func main() { // the below functions and eliminate global vars, like we do // with the cdc - rootCmd := &cobra.Command{ - Use: version.ClientName, - Short: "Command line interface for interacting with " + version.ServerName, - } + encodingConfig := app.MakeEncodingConfig() - // Add --chain-id to persistent flags and mark it required - rootCmd.PersistentFlags().String(flags.FlagChainID, "", "Chain ID of tendermint node") - rootCmd.PersistentPreRunE = func(_ *cobra.Command, _ []string) error { - return initConfig(rootCmd) + initClientCtx := client.Context{}. + WithJSONMarshaler(encodingConfig.Marshaler). + WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithTxConfig(encodingConfig.TxConfig). + WithLegacyAmino(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithBroadcastMode(flags.BroadcastBlock). + WithHomeDir(app.DefaultCLIHome) + + rootCmd := &cobra.Command{ + Use: ClientName, + Short: "Command line interface for interacting with " + version.AppName, + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { + return err + } + + return server.InterceptConfigsPreRunHandler(cmd) + }, } // Construct Root Command rootCmd.AddCommand( rpc.StatusCommand(), - client.ConfigCmd(app.DefaultCLIHome), - queryCmd(cdc), - txCmd(cdc), + queryCommand(), + txCommand(), flags.LineBreak, - lcd.ServeCommand(cdc, registerRoutes), flags.LineBreak, - keys.Commands(), + keys.Commands(app.DefaultNodeHome), flags.LineBreak, - version.Cmd, - flags.NewCompletionCmd(rootCmd, true), + //version.Cmd, + cli.NewCompletionCmd(rootCmd, true), ) - // Add flags and prefix all env exposed with WM - executor := cli.PrepareMainCmd(rootCmd, "WM", app.DefaultCLIHome) + // 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. + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{}) + ctx = context.WithValue(ctx, server.ServerContextKey, server.NewDefaultContext()) + + executor := cli.PrepareBaseCmd(rootCmd, "WM", app.DefaultCLIHome) + err := executor.ExecuteContext(ctx) - err := executor.Execute() if err != nil { fmt.Printf("Failed executing CLI command: %s, exiting...\n", err) os.Exit(1) } } -func queryCmd(cdc *amino.Codec) *cobra.Command { - queryCmd := &cobra.Command{ - Use: "query", - Aliases: []string{"q"}, - Short: "Querying subcommands", +func queryCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "query", + Aliases: []string{"q"}, + Short: "Querying subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, } - - queryCmd.AddCommand( - authcmd.GetAccountCmd(cdc), + cmd.AddCommand( + authcmd.GetAccountCmd(), flags.LineBreak, - rpc.ValidatorCommand(cdc), + rpc.ValidatorCommand(), rpc.BlockCommand(), - authcmd.QueryTxsByEventsCmd(cdc), - authcmd.QueryTxCmd(cdc), + authcmd.QueryTxsByEventsCmd(), + authcmd.QueryTxCmd(), flags.LineBreak, ) - // add modules' query commands - app.ModuleBasics.AddQueryCommands(queryCmd, cdc) + app.ModuleBasics.AddQueryCommands(cmd) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") - return queryCmd + return cmd } -func txCmd(cdc *amino.Codec) *cobra.Command { - txCmd := &cobra.Command{ - Use: "tx", - Short: "Transactions subcommands", +func txCommand() *cobra.Command { + cmd := &cobra.Command{ + Use: "tx", + Short: "Transactions subcommands", + DisableFlagParsing: true, + SuggestionsMinimumDistance: 2, + RunE: client.ValidateCmd, } - txCmd.AddCommand( - bankcmd.SendTxCmd(cdc), + cmd.AddCommand( + bankcmd.NewSendTxCmd(), flags.LineBreak, - authcmd.GetSignCommand(cdc), - authcmd.GetMultiSignCommand(cdc), + authcmd.GetSignCommand(), + authcmd.GetSignBatchCommand(), + authcmd.GetMultiSignCommand(), + authcmd.GetValidateSignaturesCommand(), flags.LineBreak, - authcmd.GetBroadcastCommand(cdc), - authcmd.GetEncodeCommand(cdc), - authcmd.GetDecodeCommand(cdc), - // TODO: I think it is safe to remove - // authcmd.GetDecodeTxCmd(cdc), + authcmd.GetBroadcastCommand(), + authcmd.GetEncodeCommand(), + authcmd.GetDecodeCommand(), flags.LineBreak, + vestingcli.GetTxCmd(), ) // add modules' tx commands - app.ModuleBasics.AddTxCommands(txCmd, cdc) + 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 txCmd.Commands() { - if cmd.Use == auth.ModuleName || cmd.Use == bank.ModuleName { + for _, cmd := range cmd.Commands() { + if cmd.Use == authtypes.ModuleName || cmd.Use == banktypes.ModuleName { cmdsToRemove = append(cmdsToRemove, cmd) } } - txCmd.RemoveCommand(cmdsToRemove...) - - return txCmd -} + cmd.RemoveCommand(cmdsToRemove...) + cmd.PersistentFlags().String(flags.FlagChainID, "", "The network chain ID") -// registerRoutes registers the routes from the different modules for the LCD. -// NOTE: details on the routes added for each module are in the module documentation -// NOTE: If making updates here you also need to update the test helper in client/lcd/test_helper.go -func registerRoutes(rs *lcd.RestServer) { - client.RegisterRoutes(rs.CliCtx, rs.Mux) - authrest.RegisterTxRoutes(rs.CliCtx, rs.Mux) - app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) -} - -func initConfig(cmd *cobra.Command) error { - home, err := cmd.PersistentFlags().GetString(cli.HomeFlag) - if err != nil { - return err - } - - cfgFile := path.Join(home, "config", "config.toml") - if _, err := os.Stat(cfgFile); err == nil { - viper.SetConfigFile(cfgFile) - - if err := viper.ReadInConfig(); err != nil { - return err - } - } - if err := viper.BindPFlag(flags.FlagChainID, cmd.PersistentFlags().Lookup(flags.FlagChainID)); err != nil { - return err - } - if err := viper.BindPFlag(cli.EncodingFlag, cmd.PersistentFlags().Lookup(cli.EncodingFlag)); err != nil { - return err - } - return viper.BindPFlag(cli.OutputFlag, cmd.PersistentFlags().Lookup(cli.OutputFlag)) + return cmd } diff --git a/cmd/wasmd/genaccounts.go b/cmd/wasmd/genaccounts.go index 031e6576de..9c8d8a2a48 100644 --- a/cmd/wasmd/genaccounts.go +++ b/cmd/wasmd/genaccounts.go @@ -2,37 +2,33 @@ package main import ( "bufio" + "encoding/json" "errors" "fmt" "github.com/spf13/cobra" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/libs/cli" + "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/keys" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" - authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" + genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" ) const ( - flagClientHome = "home-client" flagVestingStart = "vesting-start-time" flagVestingEnd = "vesting-end-time" flagVestingAmt = "vesting-amount" ) // AddGenesisAccountCmd returns add-genesis-account cobra Command. -func AddGenesisAccountCmd( - ctx *server.Context, cdc *codec.Codec, defaultNodeHome, defaultClientHome string, -) *cobra.Command { - +func AddGenesisAccountCmd(defaultNodeHome string) *cobra.Command { cmd := &cobra.Command{ Use: "add-genesis-account [address_or_key_name] [coin][,[coin]]", Short: "Add a genesis account to genesis.json", @@ -43,24 +39,27 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa `, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - config := ctx.Config - config.SetRoot(viper.GetString(cli.HomeFlag)) + clientCtx := client.GetClientContextFromCmd(cmd) + depCdc := clientCtx.JSONMarshaler + cdc := depCdc.(codec.Marshaler) + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + config.SetRoot(clientCtx.HomeDir) addr, err := sdk.AccAddressFromBech32(args[0]) - inBuf := bufio.NewReader(cmd.InOrStdin()) if err != nil { + inBuf := bufio.NewReader(cmd.InOrStdin()) + keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + // attempt to lookup address from Keybase if no address was provided - kb, err := keys.NewKeyring( - sdk.KeyringServiceName(), - viper.GetString(flags.FlagKeyringBackend), - viper.GetString(flagClientHome), - inBuf, - ) + kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, clientCtx.HomeDir, inBuf) if err != nil { return err } - info, err := kb.Get(args[0]) + info, err := kb.Key(args[0]) if err != nil { return fmt.Errorf("failed to get address from Keybase: %w", err) } @@ -73,21 +72,27 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa return fmt.Errorf("failed to parse coins: %w", err) } - vestingStart := viper.GetInt64(flagVestingStart) - vestingEnd := viper.GetInt64(flagVestingEnd) - vestingAmt, err := sdk.ParseCoins(viper.GetString(flagVestingAmt)) + vestingStart, _ := cmd.Flags().GetInt64(flagVestingStart) + vestingEnd, _ := cmd.Flags().GetInt64(flagVestingEnd) + vestingAmtStr, _ := cmd.Flags().GetString(flagVestingAmt) + + vestingAmt, err := sdk.ParseCoins(vestingAmtStr) if err != nil { return fmt.Errorf("failed to parse vesting amount: %w", err) } // create concrete account type based on input parameters - var genAccount authexported.GenesisAccount + var genAccount authtypes.GenesisAccount + + balances := banktypes.Balance{Address: addr.String(), Coins: coins.Sort()} + baseAccount := authtypes.NewBaseAccount(addr, nil, 0, 0) - baseAccount := auth.NewBaseAccount(addr, coins.Sort(), nil, 0, 0) if !vestingAmt.IsZero() { - baseVestingAccount, err := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) - if err != nil { - return fmt.Errorf("failed to create base vesting account: %w", err) + baseVestingAccount := authvesting.NewBaseVestingAccount(baseAccount, vestingAmt.Sort(), vestingEnd) + + if (balances.Coins.IsZero() && !baseVestingAccount.OriginalVesting.IsZero()) || + baseVestingAccount.OriginalVesting.IsAnyGT(balances.Coins) { + return errors.New("vesting amount cannot be greater than total amount") } switch { @@ -109,30 +114,52 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa } genFile := config.GenesisFile() - appState, genDoc, err := genutil.GenesisStateFromGenFile(cdc, genFile) + appState, genDoc, err := genutiltypes.GenesisStateFromGenFile(genFile) if err != nil { return fmt.Errorf("failed to unmarshal genesis state: %w", err) } - authGenState := auth.GetGenesisStateFromAppState(cdc, appState) + authGenState := authtypes.GetGenesisStateFromAppState(cdc, appState) + + accs, err := authtypes.UnpackAccounts(authGenState.Accounts) + if err != nil { + return fmt.Errorf("failed to get accounts from any: %w", err) + } - if authGenState.Accounts.Contains(addr) { + if accs.Contains(addr) { return fmt.Errorf("cannot add account at existing address %s", addr) } // Add the new account to the set of genesis accounts and sanitize the // accounts afterwards. - authGenState.Accounts = append(authGenState.Accounts, genAccount) - authGenState.Accounts = auth.SanitizeGenesisAccounts(authGenState.Accounts) + accs = append(accs, genAccount) + accs = authtypes.SanitizeGenesisAccounts(accs) + + genAccs, err := authtypes.PackAccounts(accs) + if err != nil { + return fmt.Errorf("failed to convert accounts into any's: %w", err) + } + authGenState.Accounts = genAccs - authGenStateBz, err := cdc.MarshalJSON(authGenState) + authGenStateBz, err := cdc.MarshalJSON(&authGenState) if err != nil { return fmt.Errorf("failed to marshal auth genesis state: %w", err) } - appState[auth.ModuleName] = authGenStateBz + appState[authtypes.ModuleName] = authGenStateBz + + bankGenState := banktypes.GetGenesisStateFromAppState(depCdc, appState) + bankGenState.Balances = append(bankGenState.Balances, balances) + bankGenState.Balances = banktypes.SanitizeGenesisBalances(bankGenState.Balances) + + bankGenStateBz, err := cdc.MarshalJSON(bankGenState) + if err != nil { + return fmt.Errorf("failed to marshal bank genesis state: %w", err) + } + + appState[banktypes.ModuleName] = bankGenStateBz - appStateJSON, err := cdc.MarshalJSON(appState) + appStateJSON, err := json.Marshal(appState) if err != nil { return fmt.Errorf("failed to marshal application genesis state: %w", err) } @@ -142,12 +169,12 @@ contain valid denominations. Accounts may optionally be supplied with vesting pa }, } - cmd.Flags().String(cli.HomeFlag, defaultNodeHome, "node's home directory") - cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") - cmd.Flags().String(flagClientHome, defaultClientHome, "client's home directory") + cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory") + cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|kwallet|pass|test)") cmd.Flags().String(flagVestingAmt, "", "amount of coins for vesting accounts") - cmd.Flags().Uint64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") - cmd.Flags().Uint64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") + cmd.Flags().Int64(flagVestingStart, 0, "schedule start time (unix epoch) for vesting accounts") + cmd.Flags().Int64(flagVestingEnd, 0, "schedule end time (unix epoch) for vesting accounts") + flags.AddQueryFlagsToCmd(cmd) return cmd } diff --git a/cmd/wasmd/main.go b/cmd/wasmd/main.go index 91493f542f..3d2d0064dc 100644 --- a/cmd/wasmd/main.go +++ b/cmd/wasmd/main.go @@ -1,116 +1,18 @@ package main import ( - "encoding/json" - "github.com/cosmos/cosmos-sdk/version" - "io" - - "github.com/CosmWasm/wasmd/app" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/server" - "github.com/cosmos/cosmos-sdk/store" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/spf13/cobra" - "github.com/spf13/viper" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" + "os" ) -const flagInvCheckPeriod = "inv-check-period" - -var invCheckPeriod uint - func main() { - cdc := app.MakeCodec() - - config := sdk.GetConfig() - config.SetBech32PrefixForAccount(app.Bech32PrefixAccAddr, app.Bech32PrefixAccPub) - config.SetBech32PrefixForValidator(app.Bech32PrefixValAddr, app.Bech32PrefixValPub) - config.SetBech32PrefixForConsensusNode(app.Bech32PrefixConsAddr, app.Bech32PrefixConsPub) - config.Seal() - - ctx := server.NewDefaultContext() - cobra.EnableCommandSorting = false - rootCmd := &cobra.Command{ - Use: version.ServerName, - Short: "Wasm Daemon (server) with wasm gov proposals disabled\",", - PersistentPreRunE: server.PersistentPreRunEFn(ctx), + rootCmd, _ := NewRootCmd() + if err := Execute(rootCmd); err != nil { + // TODO: enable this for 0.41 + //switch e := err.(type) { + //case server.ErrorCode: + // os.Exit(e.Code) + //default: + os.Exit(1) + //} } - - rootCmd.AddCommand(genutilcli.InitCmd(ctx, cdc, app.ModuleBasics, app.DefaultNodeHome)) - rootCmd.AddCommand(genutilcli.CollectGenTxsCmd(ctx, cdc, auth.GenesisAccountIterator{}, app.DefaultNodeHome)) - rootCmd.AddCommand(genutilcli.MigrateGenesisCmd(ctx, cdc)) - rootCmd.AddCommand( - genutilcli.GenTxCmd( - ctx, cdc, app.ModuleBasics, staking.AppModuleBasic{}, - auth.GenesisAccountIterator{}, app.DefaultNodeHome, app.DefaultCLIHome, - ), - ) - rootCmd.AddCommand(genutilcli.ValidateGenesisCmd(ctx, cdc, app.ModuleBasics)) - rootCmd.AddCommand(AddGenesisAccountCmd(ctx, cdc, app.DefaultNodeHome, app.DefaultCLIHome)) - rootCmd.AddCommand(flags.NewCompletionCmd(rootCmd, true)) - // rootCmd.AddCommand(testnetCmd(ctx, cdc, app.ModuleBasics, auth.GenesisAccountIterator{})) - rootCmd.AddCommand(replayCmd()) - rootCmd.AddCommand(debug.Cmd(cdc)) - - server.AddCommands(ctx, cdc, rootCmd, newApp, exportAppStateAndTMValidators) - - // prepare and add flags - executor := cli.PrepareBaseCmd(rootCmd, "WM", app.DefaultNodeHome) - rootCmd.PersistentFlags().UintVar(&invCheckPeriod, flagInvCheckPeriod, - 0, "Assert registered invariants every N blocks") - err := executor.Execute() - if err != nil { - panic(err) - } -} - -func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer) abci.Application { - var cache sdk.MultiStorePersistentCache - - if viper.GetBool(server.FlagInterBlockCache) { - cache = store.NewCommitKVStoreCacheManager() - } - pruningOpts, err := server.GetPruningOptionsFromFlags() - if err != nil { - panic(err) - } - skipUpgradeHeights := make(map[int64]bool) - for _, h := range viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { - skipUpgradeHeights[int64(h)] = true - } - - return app.NewWasmApp(logger, db, traceStore, true, invCheckPeriod, - app.GetEnabledProposals(), - skipUpgradeHeights, - baseapp.SetPruning(pruningOpts), - baseapp.SetMinGasPrices(viper.GetString(server.FlagMinGasPrices)), - baseapp.SetHaltHeight(viper.GetUint64(server.FlagHaltHeight)), - baseapp.SetHaltTime(viper.GetUint64(server.FlagHaltTime)), - baseapp.SetInterBlockCache(cache)) -} - -func exportAppStateAndTMValidators( - logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, -) (json.RawMessage, []tmtypes.GenesisValidator, error) { - - if height != -1 { - gapp := app.NewWasmApp(logger, db, traceStore, false, uint(1), app.GetEnabledProposals(), nil) - err := gapp.LoadHeight(height) - if err != nil { - return nil, nil, err - } - return gapp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) - } - - gapp := app.NewWasmApp(logger, db, traceStore, true, uint(1), app.GetEnabledProposals(), nil) - return gapp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) } diff --git a/cmd/wasmd/replay.go b/cmd/wasmd/replay.go deleted file mode 100644 index c877fcc96b..0000000000 --- a/cmd/wasmd/replay.go +++ /dev/null @@ -1,190 +0,0 @@ -package main - -import ( - "fmt" - "io" - "os" - "path/filepath" - "time" - - "github.com/CosmWasm/wasmd/app" - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/server" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - sdk "github.com/cosmos/cosmos-sdk/types" - cpm "github.com/otiai10/copy" - "github.com/spf13/cobra" - abci "github.com/tendermint/tendermint/abci/types" - tmos "github.com/tendermint/tendermint/libs/os" - "github.com/tendermint/tendermint/proxy" - tmsm "github.com/tendermint/tendermint/state" - tmstore "github.com/tendermint/tendermint/store" - tm "github.com/tendermint/tendermint/types" -) - -func replayCmd() *cobra.Command { - return &cobra.Command{ - Use: "replay ", - Short: "Replay gaia transactions", - RunE: func(_ *cobra.Command, args []string) error { - return replayTxs(args[0]) - }, - Args: cobra.ExactArgs(1), - } -} - -func replayTxs(rootDir string) error { - - if false { - // Copy the rootDir to a new directory, to preserve the old one. - fmt.Fprintln(os.Stderr, "Copying rootdir over") - oldRootDir := rootDir - rootDir = oldRootDir + "_replay" - if tmos.FileExists(rootDir) { - tmos.Exit(fmt.Sprintf("temporary copy dir %v already exists", rootDir)) - } - if err := cpm.Copy(oldRootDir, rootDir); err != nil { - return err - } - } - - configDir := filepath.Join(rootDir, "config") - dataDir := filepath.Join(rootDir, "data") - ctx := server.NewDefaultContext() - - // App DB - // appDB := dbm.NewMemDB() - fmt.Fprintln(os.Stderr, "Opening app database") - appDB, err := sdk.NewLevelDB("application", dataDir) - if err != nil { - return err - } - - // TM DB - // tmDB := dbm.NewMemDB() - fmt.Fprintln(os.Stderr, "Opening tendermint state database") - tmDB, err := sdk.NewLevelDB("state", dataDir) - if err != nil { - return err - } - - // Blockchain DB - fmt.Fprintln(os.Stderr, "Opening blockstore database") - bcDB, err := sdk.NewLevelDB("blockstore", dataDir) - if err != nil { - return err - } - - // TraceStore - var traceStoreWriter io.Writer - var traceStoreDir = filepath.Join(dataDir, "trace.log") - traceStoreWriter, err = os.OpenFile( - traceStoreDir, - os.O_WRONLY|os.O_APPEND|os.O_CREATE, - 0666, - ) - if err != nil { - return err - } - - // Application - fmt.Fprintln(os.Stderr, "Creating application") - gapp := app.NewWasmApp( - // TODO: do we want to set skipUpgradeHieghts here? - ctx.Logger, appDB, traceStoreWriter, true, uint(1), app.GetEnabledProposals(), nil, - baseapp.SetPruning(storetypes.PruneEverything)) - - // Genesis - var genDocPath = filepath.Join(configDir, "genesis.json") - genDoc, err := tm.GenesisDocFromFile(genDocPath) - if err != nil { - return err - } - genState, err := tmsm.MakeGenesisState(genDoc) - if err != nil { - return err - } - // tmsm.SaveState(tmDB, genState) - - cc := proxy.NewLocalClientCreator(gapp) - proxyApp := proxy.NewAppConns(cc) - err = proxyApp.Start() - if err != nil { - return err - } - defer func() { - err = proxyApp.Stop() - if err != nil { - return - } - }() - - state := tmsm.LoadState(tmDB) - if state.LastBlockHeight == 0 { - // Send InitChain msg - fmt.Fprintln(os.Stderr, "Sending InitChain msg") - validators := tm.TM2PB.ValidatorUpdates(genState.Validators) - csParams := tm.TM2PB.ConsensusParams(genDoc.ConsensusParams) - req := abci.RequestInitChain{ - Time: genDoc.GenesisTime, - ChainId: genDoc.ChainID, - ConsensusParams: csParams, - Validators: validators, - AppStateBytes: genDoc.AppState, - } - res, err := proxyApp.Consensus().InitChainSync(req) - if err != nil { - return err - } - newValidatorz, err := tm.PB2TM.ValidatorUpdates(res.Validators) - if err != nil { - return err - } - newValidators := tm.NewValidatorSet(newValidatorz) - - // Take the genesis state. - state = genState - state.Validators = newValidators - state.NextValidators = newValidators - } - - // Create executor - fmt.Fprintln(os.Stderr, "Creating block executor") - blockExec := tmsm.NewBlockExecutor(tmDB, ctx.Logger, proxyApp.Consensus(), nil, tmsm.MockEvidencePool{}) - - // Create block store - fmt.Fprintln(os.Stderr, "Creating block store") - blockStore := tmstore.NewBlockStore(bcDB) - - tz := []time.Duration{0, 0, 0} - for i := int(state.LastBlockHeight) + 1; ; i++ { - fmt.Fprintln(os.Stderr, "Running block ", i) - t1 := time.Now() - - // Apply block - fmt.Printf("loading and applying block %d\n", i) - blockmeta := blockStore.LoadBlockMeta(int64(i)) - if blockmeta == nil { - fmt.Printf("Couldn't find block meta %d... done?\n", i) - return nil - } - block := blockStore.LoadBlock(int64(i)) - if block == nil { - return fmt.Errorf("couldn't find block %d", i) - } - - t2 := time.Now() - - state, _, err = blockExec.ApplyBlock(state, blockmeta.BlockID, block) - if err != nil { - return err - } - - t3 := time.Now() - tz[0] += t2.Sub(t1) - tz[1] += t3.Sub(t2) - - fmt.Fprintf(os.Stderr, "new app hash: %X\n", state.AppHash) - fmt.Fprintln(os.Stderr, tz) - } -} diff --git a/cmd/wasmd/root.go b/cmd/wasmd/root.go new file mode 100644 index 0000000000..3b7911a9ad --- /dev/null +++ b/cmd/wasmd/root.go @@ -0,0 +1,171 @@ +package main + +import ( + "context" + "io" + "os" + "path/filepath" + + "github.com/CosmWasm/wasmd/app" + "github.com/cosmos/cosmos-sdk/snapshots" + "github.com/cosmos/cosmos-sdk/version" + + "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/debug" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/keys" + "github.com/cosmos/cosmos-sdk/client/rpc" + "github.com/cosmos/cosmos-sdk/server" + servertypes "github.com/cosmos/cosmos-sdk/server/types" + "github.com/cosmos/cosmos-sdk/store" + sdk "github.com/cosmos/cosmos-sdk/types" + authclient "github.com/cosmos/cosmos-sdk/x/auth/client" + "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli" +) + +// NewRootCmd creates a new root command for simd. It is called once in the +// main function. +func NewRootCmd() (*cobra.Command, app.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() + + initClientCtx := client.Context{}. + WithJSONMarshaler(encodingConfig.Marshaler). + WithInterfaceRegistry(encodingConfig.InterfaceRegistry). + WithTxConfig(encodingConfig.TxConfig). + WithLegacyAmino(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(types.AccountRetriever{}). + WithBroadcastMode(flags.BroadcastBlock). + WithHomeDir(app.DefaultNodeHome) + + rootCmd := &cobra.Command{ + Use: version.AppName, + Short: "Wasm Daemon (server)", + PersistentPreRunE: func(cmd *cobra.Command, _ []string) error { + if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil { + return err + } + + return server.InterceptConfigsPreRunHandler(cmd) + }, + } + + initRootCmd(rootCmd, encodingConfig) + return rootCmd, encodingConfig +} + +// Execute executes the root command. +func Execute(rootCmd *cobra.Command) error { + // 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. + ctx := context.Background() + ctx = context.WithValue(ctx, client.ClientContextKey, &client.Context{}) + ctx = context.WithValue(ctx, server.ServerContextKey, server.NewDefaultContext()) + + executor := tmcli.PrepareBaseCmd(rootCmd, "WM", app.DefaultNodeHome) + return executor.ExecuteContext(ctx) +} + +func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) { + authclient.Codec = encodingConfig.Marshaler + + 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, encodingConfig.TxConfig), + AddGenesisAccountCmd(app.DefaultNodeHome), + tmcli.NewCompletionCmd(rootCmd, true), + // testnetCmd(app.ModuleBasics, banktypes.GenesisBalancesIterator{}), + debug.Cmd(), + ) + + server.AddCommands(rootCmd, app.DefaultNodeHome, newApp, exportAppStateAndTMValidators) + + // add keybase, auxiliary RPC, query, and tx child commands + rootCmd.AddCommand( + rpc.StatusCommand(), + keys.Commands(app.DefaultNodeHome), + ) +} + +func 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)) { + cache = store.NewCommitKVStoreCacheManager() + } + + skipUpgradeHeights := make(map[int64]bool) + for _, h := range cast.ToIntSlice(appOpts.Get(server.FlagUnsafeSkipUpgrades)) { + skipUpgradeHeights[int64(h)] = true + } + pruningOpts, err := server.GetPruningOptionsFromFlags(appOpts) + if err != nil { + panic(err) + } + snapshotDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data", "snapshots") + snapshotDB, err := sdk.NewLevelDB("metadata", snapshotDir) + if err != nil { + panic(err) + } + snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) + if err != nil { + panic(err) + } + + return app.NewWasmApp(logger, db, traceStore, true, skipUpgradeHeights, + cast.ToString(appOpts.Get(flags.FlagHome)), + cast.ToUint(appOpts.Get(server.FlagInvCheckPeriod)), + app.GetEnabledProposals(), + baseapp.SetPruning(pruningOpts), + baseapp.SetMinGasPrices(cast.ToString(appOpts.Get(server.FlagMinGasPrices))), + baseapp.SetHaltHeight(cast.ToUint64(appOpts.Get(server.FlagHaltHeight))), + baseapp.SetHaltTime(cast.ToUint64(appOpts.Get(server.FlagHaltTime))), + baseapp.SetMinRetainBlocks(cast.ToUint64(appOpts.Get(server.FlagMinRetainBlocks))), + baseapp.SetInterBlockCache(cache), + baseapp.SetTrace(cast.ToBool(appOpts.Get(server.FlagTrace))), + baseapp.SetIndexEvents(cast.ToStringSlice(appOpts.Get(server.FlagIndexEvents))), + baseapp.SetSnapshotStore(snapshotStore), + baseapp.SetSnapshotInterval(cast.ToUint64(appOpts.Get(server.FlagStateSyncSnapshotInterval))), + baseapp.SetSnapshotKeepRecent(cast.ToUint32(appOpts.Get(server.FlagStateSyncSnapshotKeepRecent))), + ) +} + +func exportAppStateAndTMValidators( + logger log.Logger, db dbm.DB, traceStore io.Writer, height int64, forZeroHeight bool, jailWhiteList []string, +) (servertypes.ExportedApp, error) { + + var wasmApp *app.WasmApp + if height != -1 { + wasmApp = app.NewWasmApp(logger, db, traceStore, false, map[int64]bool{}, "", uint(1), app.GetEnabledProposals()) + + if err := wasmApp.LoadHeight(height); err != nil { + return servertypes.ExportedApp{}, err + } + } else { + wasmApp = app.NewWasmApp(logger, db, traceStore, true, map[int64]bool{}, "", uint(1), app.GetEnabledProposals()) + } + + return wasmApp.ExportAppStateAndValidators(forZeroHeight, jailWhiteList) +} diff --git a/cmd/wasmd/testnet.go b/cmd/wasmd/testnet.go index 3409f74e60..bf3fc5a1f1 100644 --- a/cmd/wasmd/testnet.go +++ b/cmd/wasmd/testnet.go @@ -11,7 +11,6 @@ import ( "path/filepath" "github.com/spf13/cobra" - "github.com/spf13/viper" tmconfig "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/crypto" tmos "github.com/tendermint/tendermint/libs/os" @@ -19,19 +18,20 @@ import ( "github.com/tendermint/tendermint/types" tmtime "github.com/tendermint/tendermint/types/time" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/crypto/keyring" "github.com/cosmos/cosmos-sdk/server" srvconfig "github.com/cosmos/cosmos-sdk/server/config" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" "github.com/cosmos/cosmos-sdk/x/genutil" genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types" - "github.com/cosmos/cosmos-sdk/x/staking" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) var ( @@ -39,18 +39,14 @@ var ( flagNumValidators = "v" flagOutputDir = "output-dir" flagNodeDaemonHome = "node-daemon-home" - flagNodeCLIHome = "node-cli-home" flagStartingIPAddress = "starting-ip-address" ) // get cmd to initialize all files for tendermint testnet and application -func testnetCmd(ctx *server.Context, cdc *codec.Codec, - mbm module.BasicManager, genAccIterator genutiltypes.GenesisAccountsIterator, -) *cobra.Command { - +func testnetCmd(mbm module.BasicManager, genBalIterator banktypes.GenesisBalancesIterator) *cobra.Command { cmd := &cobra.Command{ Use: "testnet", - Short: "Initialize files for a Wasmd testnet", + Short: "Initialize files for a testnet", Long: `testnet will create "v" number of directories and populate each with necessary files (private validator, genesis, config, etc.). @@ -60,65 +56,79 @@ Example: wasmd testnet --v 4 --output-dir ./output --starting-ip-address 192.168.10.2 `, RunE: func(cmd *cobra.Command, _ []string) error { - config := ctx.Config - - outputDir := viper.GetString(flagOutputDir) - chainID := viper.GetString(flags.FlagChainID) - minGasPrices := viper.GetString(server.FlagMinGasPrices) - nodeDirPrefix := viper.GetString(flagNodeDirPrefix) - nodeDaemonHome := viper.GetString(flagNodeDaemonHome) - nodeCLIHome := viper.GetString(flagNodeCLIHome) - startingIPAddress := viper.GetString(flagStartingIPAddress) - numValidators := viper.GetInt(flagNumValidators) - - return InitTestnet(cmd, config, cdc, mbm, genAccIterator, outputDir, chainID, - minGasPrices, nodeDirPrefix, nodeDaemonHome, nodeCLIHome, startingIPAddress, numValidators) + clientCtx := client.GetClientContextFromCmd(cmd) + + serverCtx := server.GetServerContextFromCmd(cmd) + config := serverCtx.Config + + outputDir, _ := cmd.Flags().GetString(flagOutputDir) + keyringBackend, _ := cmd.Flags().GetString(flags.FlagKeyringBackend) + chainID, _ := cmd.Flags().GetString(flags.FlagChainID) + minGasPrices, _ := cmd.Flags().GetString(server.FlagMinGasPrices) + nodeDirPrefix, _ := cmd.Flags().GetString(flagNodeDirPrefix) + nodeDaemonHome, _ := cmd.Flags().GetString(flagNodeDaemonHome) + startingIPAddress, _ := cmd.Flags().GetString(flagStartingIPAddress) + numValidators, _ := cmd.Flags().GetInt(flagNumValidators) + algo, _ := cmd.Flags().GetString(flags.FlagKeyAlgorithm) + + return InitTestnet( + clientCtx, cmd, config, mbm, genBalIterator, outputDir, chainID, minGasPrices, + nodeDirPrefix, nodeDaemonHome, startingIPAddress, keyringBackend, algo, numValidators, + ) }, } - cmd.Flags().Int(flagNumValidators, 4, - "Number of validators to initialize the testnet with") - cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", - "Directory to store initialization data for the testnet") - cmd.Flags().String(flagNodeDirPrefix, "node", - "Prefix the directory name for each node with (node results in node0, node1, ...)") - cmd.Flags().String(flagNodeDaemonHome, "wasmd", - "Home directory of the node's daemon configuration") - cmd.Flags().String(flagNodeCLIHome, "wasmcli", - "Home directory of the node's cli configuration") - cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", - "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") - cmd.Flags().String( - flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") - cmd.Flags().String( - server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), - "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") + cmd.Flags().Int(flagNumValidators, 4, "Number of validators to initialize the testnet with") + cmd.Flags().StringP(flagOutputDir, "o", "./mytestnet", "Directory to store initialization data for the testnet") + cmd.Flags().String(flagNodeDirPrefix, "node", "Prefix the directory name for each node with (node results in node0, node1, ...)") + cmd.Flags().String(flagNodeDaemonHome, "simd", "Home directory of the node's daemon configuration") + cmd.Flags().String(flagStartingIPAddress, "192.168.0.1", "Starting IP address (192.168.0.1 results in persistent peers list ID0@192.168.0.1:46656, ID1@192.168.0.2:46656, ...)") + cmd.Flags().String(flags.FlagChainID, "", "genesis file chain-id, if left blank will be randomly created") + cmd.Flags().String(server.FlagMinGasPrices, fmt.Sprintf("0.000006%s", sdk.DefaultBondDenom), "Minimum gas prices to accept for transactions; All fees in a tx must meet this minimum (e.g. 0.01photino,0.001stake)") cmd.Flags().String(flags.FlagKeyringBackend, flags.DefaultKeyringBackend, "Select keyring's backend (os|file|test)") + cmd.Flags().String(flags.FlagKeyAlgorithm, string(hd.Secp256k1Type), "Key signing algorithm to generate keys for") + return cmd } const nodeDirPerm = 0755 // Initialize the testnet -func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, - mbm module.BasicManager, genAccIterator genutiltypes.GenesisAccountsIterator, - outputDir, chainID, minGasPrices, nodeDirPrefix, nodeDaemonHome, - nodeCLIHome, startingIPAddress string, numValidators int) error { +func InitTestnet( + clientCtx client.Context, + cmd *cobra.Command, + nodeConfig *tmconfig.Config, + mbm module.BasicManager, + genBalIterator banktypes.GenesisBalancesIterator, + outputDir, + chainID, + minGasPrices, + nodeDirPrefix, + nodeDaemonHome, + startingIPAddress, + keyringBackend, + algoStr string, + numValidators int, +) error { if chainID == "" { - chainID = "chain-" + tmrand.Str(6) + chainID = "chain-" + tmrand.NewRand().Str(6) } - monikers := make([]string, numValidators) nodeIDs := make([]string, numValidators) valPubKeys := make([]crypto.PubKey, numValidators) - wasmConfig := srvconfig.DefaultConfig() - wasmConfig.MinGasPrices = minGasPrices + simappConfig := srvconfig.DefaultConfig() + simappConfig.MinGasPrices = minGasPrices + simappConfig.API.Enable = true + simappConfig.Telemetry.Enabled = true + simappConfig.Telemetry.PrometheusRetentionTime = 60 + simappConfig.Telemetry.EnableHostnameLabel = false + simappConfig.Telemetry.GlobalLabels = [][]string{{"chain_id", chainID}} - //nolint:prealloc var ( - genAccounts []authexported.GenesisAccount + genAccounts []authtypes.GenesisAccount + genBalances []banktypes.Balance genFiles []string ) @@ -127,24 +137,17 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, for i := 0; i < numValidators; i++ { nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome) - clientDir := filepath.Join(outputDir, nodeDirName, nodeCLIHome) gentxsDir := filepath.Join(outputDir, "gentxs") - config.SetRoot(nodeDir) - config.RPC.ListenAddress = "tcp://0.0.0.0:26657" + nodeConfig.SetRoot(nodeDir) + nodeConfig.RPC.ListenAddress = "tcp://0.0.0.0:26657" if err := os.MkdirAll(filepath.Join(nodeDir, "config"), nodeDirPerm); err != nil { _ = os.RemoveAll(outputDir) return err } - if err := os.MkdirAll(clientDir, nodeDirPerm); err != nil { - _ = os.RemoveAll(outputDir) - return err - } - - monikers = append(monikers, nodeDirName) - config.Moniker = nodeDirName + nodeConfig.Moniker = nodeDirName ip, err := getIP(i, startingIPAddress) if err != nil { @@ -152,27 +155,27 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, return err } - nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(config) + nodeIDs[i], valPubKeys[i], err = genutil.InitializeNodeValidatorFiles(nodeConfig) if err != nil { _ = os.RemoveAll(outputDir) return err } memo := fmt.Sprintf("%s@%s:26656", nodeIDs[i], ip) - genFiles = append(genFiles, config.GenesisFile()) + genFiles = append(genFiles, nodeConfig.GenesisFile()) - kb, err := keys.NewKeyring( - sdk.KeyringServiceName(), - viper.GetString(flags.FlagKeyringBackend), - viper.GetString(flagClientHome), - inBuf, - ) + kb, err := keyring.New(sdk.KeyringServiceName(), keyringBackend, nodeDir, inBuf) if err != nil { return err } - keyPass := clientkeys.DefaultKeyPass - addr, secret, err := server.GenerateSaveCoinKey(kb, nodeDirName, keyPass, true) + keyringAlgos, _ := kb.SupportedAlgorithms() + algo, err := keyring.NewSigningAlgoFromString(algoStr, keyringAlgos) + if err != nil { + return err + } + + addr, secret, err := server.GenerateSaveCoinKey(kb, nodeDirName, true, algo) if err != nil { _ = os.RemoveAll(outputDir) return err @@ -186,7 +189,7 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, } // save private key seed words - if err := writeFile(fmt.Sprintf("%v.json", "key_seed"), clientDir, cliPrint); err != nil { + if err := writeFile(fmt.Sprintf("%v.json", "key_seed"), nodeDir, cliPrint); err != nil { return err } @@ -196,52 +199,57 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, sdk.NewCoin(fmt.Sprintf("%stoken", nodeDirName), accTokens), sdk.NewCoin(sdk.DefaultBondDenom, accStakingTokens), } - genAccounts = append(genAccounts, auth.NewBaseAccount(addr, coins.Sort(), nil, 0, 0)) + + genBalances = append(genBalances, banktypes.Balance{Address: addr.String(), Coins: coins.Sort()}) + genAccounts = append(genAccounts, authtypes.NewBaseAccount(addr, nil, 0, 0)) valTokens := sdk.TokensFromConsensusPower(100) - msg := staking.NewMsgCreateValidator( + createValMsg := stakingtypes.NewMsgCreateValidator( sdk.ValAddress(addr), valPubKeys[i], sdk.NewCoin(sdk.DefaultBondDenom, valTokens), - staking.NewDescription(nodeDirName, "", "", "", ""), - staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + stakingtypes.NewDescription(nodeDirName, "", "", "", ""), + stakingtypes.NewCommissionRates(sdk.OneDec(), sdk.OneDec(), sdk.OneDec()), sdk.OneInt(), ) - tx := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{}, memo) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithChainID(chainID).WithMemo(memo).WithKeybase(kb) + txBuilder := clientCtx.TxConfig.NewTxBuilder() + if err := txBuilder.SetMsgs(createValMsg); err != nil { + return err + } - signedTx, err := txBldr.SignStdTx(nodeDirName, clientkeys.DefaultKeyPass, tx, false) - if err != nil { - _ = os.RemoveAll(outputDir) + txBuilder.SetMemo(memo) + + txFactory := tx.Factory{} + txFactory = txFactory. + WithChainID(chainID). + WithMemo(memo). + WithKeybase(kb). + WithTxConfig(clientCtx.TxConfig) + + if err := tx.Sign(txFactory, nodeDirName, txBuilder); err != nil { return err } - txBytes, err := cdc.MarshalJSON(signedTx) + txBz, err := clientCtx.TxConfig.TxJSONEncoder()(txBuilder.GetTx()) if err != nil { - _ = os.RemoveAll(outputDir) return err } - // gather gentxs folder - if err := writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBytes); err != nil { - _ = os.RemoveAll(outputDir) + if err := writeFile(fmt.Sprintf("%v.json", nodeDirName), gentxsDir, txBz); err != nil { return err } - // TODO: Rename config file to server.toml as it's not particular to Gaia - // (REF: https://github.com/cosmos/cosmos-sdk/issues/4125). - wasmConfigFilePath := filepath.Join(nodeDir, "config/wasmd.toml") - srvconfig.WriteConfigFile(wasmConfigFilePath, wasmConfig) + srvconfig.WriteConfigFile(filepath.Join(nodeDir, "config/app.toml"), simappConfig) } - if err := initGenFiles(cdc, mbm, chainID, genAccounts, genFiles, numValidators); err != nil { + if err := initGenFiles(clientCtx, mbm, chainID, genAccounts, genBalances, genFiles, numValidators); err != nil { return err } err := collectGenFiles( - cdc, config, chainID, monikers, nodeIDs, valPubKeys, numValidators, - outputDir, nodeDirPrefix, nodeDaemonHome, genAccIterator, + clientCtx, nodeConfig, chainID, nodeIDs, valPubKeys, numValidators, + outputDir, nodeDirPrefix, nodeDaemonHome, genBalIterator, ) if err != nil { return err @@ -252,20 +260,33 @@ func InitTestnet(cmd *cobra.Command, config *tmconfig.Config, cdc *codec.Codec, } func initGenFiles( - cdc *codec.Codec, mbm module.BasicManager, chainID string, - genAccounts []authexported.GenesisAccount, genFiles []string, numValidators int, + clientCtx client.Context, mbm module.BasicManager, chainID string, + genAccounts []authtypes.GenesisAccount, genBalances []banktypes.Balance, + genFiles []string, numValidators int, ) error { - appGenState := mbm.DefaultGenesis() + appGenState := mbm.DefaultGenesis(clientCtx.JSONMarshaler) // set the accounts in the genesis state - authDataBz := appGenState[auth.ModuleName] - var authGenState auth.GenesisState - cdc.MustUnmarshalJSON(authDataBz, &authGenState) - authGenState.Accounts = genAccounts - appGenState[auth.ModuleName] = cdc.MustMarshalJSON(authGenState) + var authGenState authtypes.GenesisState + clientCtx.JSONMarshaler.MustUnmarshalJSON(appGenState[authtypes.ModuleName], &authGenState) + + accounts, err := authtypes.PackAccounts(genAccounts) + if err != nil { + return err + } + + authGenState.Accounts = accounts + appGenState[authtypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(&authGenState) - appGenStateJSON, err := codec.MarshalJSONIndent(cdc, appGenState) + // set the balances in the genesis state + var bankGenState banktypes.GenesisState + clientCtx.JSONMarshaler.MustUnmarshalJSON(appGenState[banktypes.ModuleName], &bankGenState) + + bankGenState.Balances = genBalances + appGenState[banktypes.ModuleName] = clientCtx.JSONMarshaler.MustMarshalJSON(&bankGenState) + + appGenStateJSON, err := json.MarshalIndent(appGenState, "", " ") if err != nil { return err } @@ -286,10 +307,10 @@ func initGenFiles( } func collectGenFiles( - cdc *codec.Codec, config *tmconfig.Config, chainID string, - monikers, nodeIDs []string, valPubKeys []crypto.PubKey, - numValidators int, outputDir, nodeDirPrefix, nodeDaemonHome string, - genAccIterator genutiltypes.GenesisAccountsIterator) error { + clientCtx client.Context, nodeConfig *tmconfig.Config, chainID string, + nodeIDs []string, valPubKeys []crypto.PubKey, numValidators int, + outputDir, nodeDirPrefix, nodeDaemonHome string, genBalIterator banktypes.GenesisBalancesIterator, +) error { var appState json.RawMessage genTime := tmtime.Now() @@ -298,20 +319,19 @@ func collectGenFiles( nodeDirName := fmt.Sprintf("%s%d", nodeDirPrefix, i) nodeDir := filepath.Join(outputDir, nodeDirName, nodeDaemonHome) gentxsDir := filepath.Join(outputDir, "gentxs") - moniker := monikers[i] - config.Moniker = nodeDirName + nodeConfig.Moniker = nodeDirName - config.SetRoot(nodeDir) + nodeConfig.SetRoot(nodeDir) nodeID, valPubKey := nodeIDs[i], valPubKeys[i] - initCfg := genutil.NewInitConfig(chainID, gentxsDir, moniker, nodeID, valPubKey) + initCfg := genutiltypes.NewInitConfig(chainID, gentxsDir, nodeID, valPubKey) - genDoc, err := types.GenesisDocFromFile(config.GenesisFile()) + genDoc, err := types.GenesisDocFromFile(nodeConfig.GenesisFile()) if err != nil { return err } - nodeAppState, err := genutil.GenAppStateFromConfig(cdc, config, initCfg, *genDoc, genAccIterator) + nodeAppState, err := genutil.GenAppStateFromConfig(clientCtx.JSONMarshaler, clientCtx.TxConfig, nodeConfig, initCfg, *genDoc, genBalIterator) if err != nil { return err } @@ -321,7 +341,7 @@ func collectGenFiles( appState = nodeAppState } - genFile := config.GenesisFile() + genFile := nodeConfig.GenesisFile() // overwrite each validator's genesis file to have a canonical genesis time if err := genutil.ExportGenesisFileWithTime(genFile, chainID, nil, appState, genTime); err != nil { @@ -360,12 +380,12 @@ func writeFile(name string, dir string, contents []byte) error { writePath := filepath.Join(dir) file := filepath.Join(writePath, name) - err := tmos.EnsureDir(writePath, 0700) + err := tmos.EnsureDir(writePath, 0755) if err != nil { return err } - err = tmos.WriteFile(file, contents, 0600) + err = tmos.WriteFile(file, contents, 0644) if err != nil { return err } diff --git a/contrib/local/01-accounts.sh b/contrib/local/01-accounts.sh new file mode 100755 index 0000000000..547021debe --- /dev/null +++ b/contrib/local/01-accounts.sh @@ -0,0 +1,18 @@ +#!/bin/bash +set -o errexit -o nounset -o pipefail + +BASE_ACCOUNT=$(wasmcli keys show validator -a) +wasmcli q account "$BASE_ACCOUNT" -o json | jq + +echo "## Add new account" +wasmcli keys add fred + +echo "## Check balance" +NEW_ACCOUNT=$(wasmcli keys show fred -a) +wasmcli q bank balances "$NEW_ACCOUNT" -o json || true + +echo "## Transfer tokens" +wasmcli tx send validator "$NEW_ACCOUNT" 1ustake --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block | jq + +echo "## Check balance again" +wasmcli q bank balances "$NEW_ACCOUNT" -o json | jq diff --git a/contrib/local/02-contracts.sh b/contrib/local/02-contracts.sh new file mode 100755 index 0000000000..b0322eb381 --- /dev/null +++ b/contrib/local/02-contracts.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -o errexit -o nounset -o pipefail + +DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)" + +echo "-----------------------" +echo "## Add new CosmWasm contract" +RESP=$(wasmcli tx wasm store "$DIR/../../x/wasm/internal/keeper/testdata/hackatom.wasm" \ + --from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block) + +CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[0].attributes[-1].value') +echo "* Code id: $CODE_ID" +echo "* Download code" +TMPDIR=$(mktemp -t wasmcliXXXX) +wasmcli q wasm code "$CODE_ID" "$TMPDIR" +rm -f "$TMPDIR" +echo "-----------------------" +echo "## List code" +wasmcli query wasm list-code --node=http://localhost:26657 --chain-id=testing | jq + +echo "-----------------------" +echo "## Create new contract instance" +INIT="{\"verifier\":\"$(wasmcli keys show validator -a)\", \"beneficiary\":\"$(wasmcli keys show fred -a)\"}" +wasmcli tx wasm instantiate "$CODE_ID" "$INIT" --admin=$(wasmcli keys show validator -a) \ + --from validator --amount="100ustake" --label "local0.1.0" \ + --gas 1000000 -y --chain-id=testing -b block | jq + +CONTRACT=$(wasmcli query wasm list-contract-by-code "$CODE_ID" -o json | jq -r '.[0].address') +echo "* Contract address: $CONTRACT" +echo "### Query all" +RESP=$(wasmcli query wasm contract-state all "$CONTRACT" -o json) +echo "$RESP" +echo "### Query smart" +wasmcli query wasm contract-state smart "$CONTRACT" '{"verifier":{}}' -o json | jq +echo "### Query raw" +KEY=$(echo "$RESP" | jq -r ".[0].Key") +wasmcli query wasm contract-state raw "$CONTRACT" "$KEY" -o json + + +echo "-----------------------" +echo "## Execute contract $CONTRACT" +MSG='{"release":{}}' +wasmcli tx wasm execute "$CONTRACT" "$MSG" \ + --from validator \ + --gas 1000000 -y --chain-id=testing -b block | jq + + +echo "-----------------------" +echo "## Set new admin" +echo "### Query old admin: $(wasmcli q wasm contract $CONTRACT -o json | jq -r '.admin')" +echo "### Update contract" +wasmcli tx wasm set-contract-admin "$CONTRACT" $(wasmcli keys show fred -a) \ + --from validator -y --chain-id=testing -b block | jq +echo "### Query new admin: $(wasmcli q wasm contract $CONTRACT -o json | jq -r '.admin')" + + +echo "-----------------------" +echo "## Migrate contract" +echo "### Upload new code" +RESP=$(wasmcli tx wasm store "$DIR/../../x/wasm/internal/keeper/testdata/burner.wasm" \ + --from validator --gas 1000000 -y --chain-id=testing --node=http://localhost:26657 -b block) + +BURNER_CODE_ID=$(echo "$RESP" | jq -r '.logs[0].events[0].attributes[-1].value') +echo "### Migrate to code id: $BURNER_CODE_ID" + +DEST_ACCOUNT=$(wasmcli keys show fred -a) +wasmcli tx wasm migrate "$CONTRACT" "$BURNER_CODE_ID" "{\"payout\": \"$DEST_ACCOUNT\"}" --from fred \ + --chain-id=testing -b block -y | jq + +echo "### Query destination account: $BURNER_CODE_ID" +wasmcli q bank balances "$DEST_ACCOUNT" -o json | jq +echo "### Query contract meta data: $CONTRACT" +wasmcli q wasm contract "$CONTRACT" -o json | jq + +echo "### Query contract meta history: $CONTRACT" +wasmcli q wasm contract-history "$CONTRACT" -o json | jq + +echo "-----------------------" +echo "## Clear contract admin" +echo "### Query old admin: $(wasmcli q wasm contract $CONTRACT -o json | jq -r '.admin')" +echo "### Update contract" +wasmcli tx wasm clear-contract-admin "$CONTRACT" \ + --from fred -y --chain-id=testing -b block | jq +echo "### Query new admin: $(wasmcli q wasm contract $CONTRACT -o json | jq -r '.admin')" diff --git a/contrib/local/README.md b/contrib/local/README.md new file mode 100644 index 0000000000..3bcb924dac --- /dev/null +++ b/contrib/local/README.md @@ -0,0 +1,22 @@ +# Dev scripts +For manual testing. Works on my box(*) ... + + + +*) OSX + +``` +make install +cd contrib/local +rm -rf /tmp/trash +HOME=/tmp/trash bash setup_wasmd.sh +HOME=/tmp/trash bash start_node.sh +``` + +Next shell: + +``` +cd contrib/local +./01-accounts.sh +./02-contracts.sh +``` \ No newline at end of file diff --git a/contrib/local/setup_wasmd.sh b/contrib/local/setup_wasmd.sh new file mode 100755 index 0000000000..34c581d65f --- /dev/null +++ b/contrib/local/setup_wasmd.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -o errexit -o nounset -o pipefail + +PASSWORD=${PASSWORD:-1234567890} +STAKE=${STAKE_TOKEN:-ustake} +FEE=${FEE_TOKEN:-ucosm} +CHAIN_ID=${CHAIN_ID:-testing} +MONIKER=${MONIKER:-node001} + +wasmd init --chain-id "$CHAIN_ID" "$MONIKER" +# staking/governance token is hardcoded in config, change this +## OSX requires: -i. +sed -i. "s/\"stake\"/\"$STAKE\"/" "$HOME"/.wasmd/config/genesis.json +if ! wasmcli keys show validator; then + (echo "$PASSWORD"; echo "$PASSWORD") | wasmcli keys add validator +fi +# hardcode the validator account for this instance +echo "$PASSWORD" | wasmd add-genesis-account validator "1000000000$STAKE,1000000000$FEE" +# (optionally) add a few more genesis accounts +for addr in "$@"; do + echo $addr + wasmd add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" +done +# submit a genesis validator tx +(echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | wasmd gentx validator --chain-id=testing --amount "250000000$STAKE" +wasmd collect-gentxs diff --git a/contrib/local/start_node.sh b/contrib/local/start_node.sh new file mode 100755 index 0000000000..8db3f89cc6 --- /dev/null +++ b/contrib/local/start_node.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu + +wasmd start --rpc.laddr tcp://0.0.0.0:26657 --trace # does not work anymore: --log_level="main:info,state:debug,*:error" \ No newline at end of file diff --git a/docker/run_all.sh b/docker/run_all.sh deleted file mode 100755 index f183d532e2..0000000000 --- a/docker/run_all.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh -#set -euo pipefail - -mkdir -p /root/log -touch /root/log/wasmd.log -./run_wasmd.sh $1 >> /root/log/wasmd.log & - -sleep 4 -echo Starting Rest Server... - -./run_rest_server.sh diff --git a/docker/setup_wasmd.sh b/docker/setup_wasmd.sh index b7101b0cc6..5ef10c612b 100755 --- a/docker/setup_wasmd.sh +++ b/docker/setup_wasmd.sh @@ -21,5 +21,5 @@ for addr in "$@"; do wasmd add-genesis-account "$addr" "1000000000$STAKE,1000000000$FEE" done # submit a genesis validator tx -(echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | wasmd gentx --name validator --amount "250000000$STAKE" +(echo "$PASSWORD"; echo "$PASSWORD"; echo "$PASSWORD") | wasmd gentx validator --chain-id=testing --amount "250000000$STAKE" wasmd collect-gentxs diff --git a/go.mod b/go.mod index db3f22d351..dc700a9709 100644 --- a/go.mod +++ b/go.mod @@ -1,32 +1,30 @@ module github.com/CosmWasm/wasmd -go 1.14 +go 1.15 require ( github.com/CosmWasm/go-cosmwasm v0.11.0 - github.com/cosmos/cosmos-sdk v0.39.1-0.20200727135228-9d00f712e334 - github.com/golang/mock v1.4.3 // indirect + github.com/cosmos/cosmos-sdk v0.40.0-rc1 + github.com/cosmos/iavl v0.15.0-rc4 + github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b + github.com/gogo/protobuf v1.3.1 + github.com/golang/protobuf v1.4.3 github.com/google/gofuzz v1.0.0 - github.com/gorilla/mux v1.7.4 - github.com/magiconair/properties v1.8.1 - github.com/onsi/ginkgo v1.8.0 // indirect - github.com/onsi/gomega v1.5.0 // indirect - github.com/otiai10/copy v1.0.2 - github.com/otiai10/curr v0.0.0-20190513014714-f5a3d24e5776 // indirect + github.com/gorilla/mux v1.8.0 + github.com/grpc-ecosystem/grpc-gateway v1.15.2 github.com/pkg/errors v0.9.1 + github.com/rakyll/statik v0.1.7 github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa - github.com/spf13/afero v1.2.2 // indirect - github.com/spf13/cobra v1.0.0 + github.com/spf13/cast v1.3.1 + github.com/spf13/cobra v1.1.0 github.com/spf13/pflag v1.0.5 - github.com/spf13/viper v1.6.3 + github.com/spf13/viper v1.7.1 github.com/stretchr/testify v1.6.1 - github.com/tendermint/go-amino v0.15.1 - github.com/tendermint/iavl v0.14.0 - github.com/tendermint/tendermint v0.33.6 - github.com/tendermint/tm-db v0.5.1 - go.etcd.io/bbolt v1.3.4 // indirect - golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 // indirect + github.com/tendermint/tendermint v0.34.0-rc5 + github.com/tendermint/tm-db v0.6.2 + google.golang.org/genproto v0.0.0-20201014134559-03b6142f0dc9 + google.golang.org/grpc v1.33.0 gopkg.in/yaml.v2 v2.3.0 ) -replace github.com/keybase/go-keychain => github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 +replace github.com/gogo/protobuf => github.com/regen-network/protobuf v1.3.2-alpha.regen.4 diff --git a/go.sum b/go.sum index 7a1bc9d617..0f6ee90a24 100644 --- a/go.sum +++ b/go.sum @@ -1,25 +1,31 @@ -bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs= -github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4/go.mod h1:hN7oaIRCjzsZ2dE+yG5k+rsdt3qcwykqK6HVGcKwsw4= -github.com/99designs/keyring v1.1.3 h1:mEV3iyZWjkxQ7R8ia8GcG97vCX5zQQ7n4o8R2BylwQY= -github.com/99designs/keyring v1.1.3/go.mod h1:657DQuMrBZRtuL/voxVyiyb6zpMehlm5vLB9Qwrv904= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +github.com/99designs/keyring v1.1.6 h1:kVDC2uCgVwecxCk+9zoCt2uEL6dt+dfVzMvGgnVcIuM= +github.com/99designs/keyring v1.1.6/go.mod h1:16e0ds7LGQQcT59QqkTg72Hh5ShM51Byv5PEmW6uoRU= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d h1:nalkkPQcITbvhmL4+C4cKA87NW0tfm3Kl9VXRoPywFg= github.com/ChainSafe/go-schnorrkel v0.0.0-20200405005733-88cbf1b4c40d/go.mod h1:URdX5+vg25ts3aCh8H5IFZybJYKWhJHYMTnf+ULtoC4= -github.com/CosmWasm/go-cosmwasm v0.10.0 h1:3DBOiGtLllevLgf8PQO5+hRCKKqYEQJIw6cgaZzr1Ag= -github.com/CosmWasm/go-cosmwasm v0.10.0/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= -github.com/CosmWasm/go-cosmwasm v0.11.0-alpha1 h1:5c87JcnA+ncQlSJO/mEK6z9oIi/oS46CCsYduvRgPvw= -github.com/CosmWasm/go-cosmwasm v0.11.0-alpha1/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= -github.com/CosmWasm/go-cosmwasm v0.11.0-alpha2 h1:w42GtYC4P/6dXOVlqEutr96tSsy/EO0aC9d3sbkk5hs= -github.com/CosmWasm/go-cosmwasm v0.11.0-alpha2/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= -github.com/CosmWasm/go-cosmwasm v0.11.0-rc h1:qKMUR/84LluMStwuOgaWxupQj8STmnRaxFgFXrhY95o= -github.com/CosmWasm/go-cosmwasm v0.11.0-rc/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= github.com/CosmWasm/go-cosmwasm v0.11.0 h1:H+7Xzh2tEquJXuP4q1VN7ekdheAQvCjD4FRmlPqcXnQ= github.com/CosmWasm/go-cosmwasm v0.11.0/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= +github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ= +github.com/DataDog/zstd v1.4.1/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/DataDog/zstd v1.4.5 h1:EndNeuB0l9syBZhut0wns3gV1hL8zX8LIu6ZiVHWLIQ= +github.com/DataDog/zstd v1.4.5/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= +github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= @@ -33,36 +39,41 @@ github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuy github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/apache/thrift v0.13.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= +github.com/armon/go-metrics v0.3.4 h1:Xqf+7f2Vhl9tsqDYmXhnXInUdcrtgpRNpIA15/uldSc= +github.com/armon/go-metrics v0.3.4/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb4QAOwNTFc= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aryann/difflib v0.0.0-20170710044230-e206f873d14a/go.mod h1:DAHtR1m6lCRdSC2Tm3DSWRPvIPr6xNKyeHdqDQSQT+A= github.com/aws/aws-lambda-go v1.13.3/go.mod h1:4UKl9IzQMoD+QF79YdCuzCwp8VbmG4VAQwij/eHl5CU= github.com/aws/aws-sdk-go v1.27.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= github.com/aws/aws-sdk-go-v2 v0.18.0/go.mod h1:JWVYvqSMppoMJC0x5wdwiImzgXTI9FuZwxzkQq9wy+g= -github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d h1:1aAija9gr0Hyv4KfQcRcwlmFIrhkDmIj2dz5bkg/s/8= -github.com/bartekn/go-bip39 v0.0.0-20171116152956-a05967ea095d/go.mod h1:icNx/6QdFblhsEjZehARqbNumymUT/ydwlLojFdv7Sk= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= +github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84= github.com/btcsuite/btcd v0.0.0-20190115013929-ed77733ec07d/go.mod h1:d3C0AkH6BRcvO8T0UEPu53cnw4IbV63x1bEjildYhO0= -github.com/btcsuite/btcd v0.20.1-beta h1:Ik4hyJqN8Jfyv3S4AGBOmyouMsYE3EdYODkMbQjwPGw= github.com/btcsuite/btcd v0.20.1-beta/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ= +github.com/btcsuite/btcd v0.21.0-beta h1:At9hIZdJW0s9E/fAz28nrz6AmcNlSVucCH796ZteX1M= +github.com/btcsuite/btcd v0.21.0-beta/go.mod h1:ZSWyehm27aAuS9bvkATT+Xte3hjHZ+MRgMY/8NJ7K94= github.com/btcsuite/btclog v0.0.0-20170628155309-84c8d2346e9f/go.mod h1:TdznJufoqS23FtqVCzL0ZqgP5MqXbb4fg/WgDys70nA= github.com/btcsuite/btcutil v0.0.0-20180706230648-ab6388e0c60a/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= -github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d h1:yJzD/yFppdVCf6ApMkVy8cUxV0XrxdP9rVf6D87/Mng= github.com/btcsuite/btcutil v0.0.0-20190425235716-9e5f4b9a998d/go.mod h1:+5NJ2+qvTyV9exUAL/rxXi3DcLg2Ts+ymUAY5y4NvMg= github.com/btcsuite/btcutil v1.0.2 h1:9iZ1Terx9fMIOtq1VrwdqfsATL9MC2l8ZrUY6YZ2uts= github.com/btcsuite/btcutil v1.0.2/go.mod h1:j9HUFwoQRsZL3V4n+qG+CUnEGHOarIxfC3Le2Yhbcts= github.com/btcsuite/go-socks v0.0.0-20170105172521-4720035b7bfd/go.mod h1:HHNXQzUsZCxOoE+CPiyCTO6x34Zs86zZUiwtpXoGdtg= github.com/btcsuite/goleveldb v0.0.0-20160330041536-7834afc9e8cd/go.mod h1:F+uVaaLLH7j4eDXPRvw78tMflu7Ie2bzYOH4Y8rRKBY= +github.com/btcsuite/goleveldb v1.0.0/go.mod h1:QiK9vBlgftBg6rWQIj6wFzbPfRjiykIEhBH4obrXJ/I= github.com/btcsuite/snappy-go v0.0.0-20151229074030-0bdef8d06723/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= +github.com/btcsuite/snappy-go v1.0.0/go.mod h1:8woku9dyThutzjeg+3xrA5iCpBRH8XEEg3lh6TiUghc= github.com/btcsuite/websocket v0.0.0-20150119174127-31079b680792/go.mod h1:ghJtEyQwv5/p4Mg4C0fgbePVuGr935/5ddU9Z3TmDRY= github.com/btcsuite/winsvc v1.0.0/go.mod h1:jsenWakMcC0zFBFurPLEAyrnc/teJEM1O46fmI40EZs= github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ= @@ -72,27 +83,42 @@ github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/circonus-labs/circonus-gometrics v2.3.1+incompatible/go.mod h1:nmEj6Dob7S7YxXgwXpfOuvO54S+tGdZdw9fuRZt25Ag= +github.com/circonus-labs/circonusllhist v0.1.3/go.mod h1:kMXHVDlOchFAehlya5ePtbp5jckzBHf4XRpQvBOLI+I= github.com/clbanning/x2j v0.0.0-20191024224557-825249438eec/go.mod h1:jMjuTZXRI4dUb/I5gc9Hdhagfvm9+RyrPryS/auMzxE= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8= github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/confio/ics23/go v0.0.0-20200817220745-f173e6211efb h1:+7FsS1gZ1Km5LRjGV2hztpier/5i6ngNjvNpxbWP5I0= +github.com/confio/ics23/go v0.0.0-20200817220745-f173e6211efb/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= +github.com/confio/ics23/go v0.6.3 h1:PuGK2V1NJWZ8sSkNDq91jgT/cahFEW9RGp4Y5jxulf0= +github.com/confio/ics23/go v0.6.3/go.mod h1:E45NqnlpxGnpfTWL/xauN7MRwEE28T4Dd4uraToOaKg= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cosmos/cosmos-sdk v0.39.1-0.20200727135228-9d00f712e334 h1:JwuojvDWZiFn8hR91yUkkXVIY7d9DisZ+g2J9iDn+Ps= -github.com/cosmos/cosmos-sdk v0.39.1-0.20200727135228-9d00f712e334/go.mod h1:soj4C8lIjJLeUQPBqrM+krbXdnF4cDKaaDgg1JIJYRU= +github.com/cosmos/cosmos-sdk v0.34.4-0.20201016130402-6e569e125571 h1:S8nqAPT01CVOC6jEnRYGHySkpezC8lu6Xt3dfnei95M= +github.com/cosmos/cosmos-sdk v0.34.4-0.20201016130402-6e569e125571/go.mod h1:4UED4atks+Y3NgLdCFkVqNHdjXTHDO2c+r3ydaFh0QE= +github.com/cosmos/cosmos-sdk v0.40.0-rc1 h1:DbM2vbmx9soER38YkdLB5g9d+YhaDlKAl2Pne5RLcEQ= +github.com/cosmos/cosmos-sdk v0.40.0-rc1/go.mod h1:4wGruNUDrenXKRl/F7ujW29lTv3C+6/TDWs3QfZZN2Y= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d h1:49RLWk1j44Xu4fjHb6JFYmeUnDORVwHNkDxaQ0ctCVU= github.com/cosmos/go-bip39 v0.0.0-20180819234021-555e2067c45d/go.mod h1:tSxLoYXyBmiFeKpvmq4dzayMdCjCnu8uqmCysIGBT2Y= +github.com/cosmos/iavl v0.15.0-rc3 h1:rSm60IFfDCD9qDfvXKEmaJhcv0rB5uCbVlBDKsynxqw= +github.com/cosmos/iavl v0.15.0-rc3/go.mod h1:rQ2zK/LuivThMjve3Yr6VkjvCqCXl+fgHCY7quiUA68= +github.com/cosmos/iavl v0.15.0-rc4 h1:P1wmET7BueqCzfxsn+BzVkDWDLY9ij2JNwkbIdM7RG8= +github.com/cosmos/iavl v0.15.0-rc4/go.mod h1:5CsecJdh44Uj4vZ6WSPeWq84hNW5BwRI36ZsAbfJvRw= github.com/cosmos/ledger-cosmos-go v0.11.1 h1:9JIYsGnXP613pb2vPjFeMMjBI5lEDsEaF6oYorTy6J4= github.com/cosmos/ledger-cosmos-go v0.11.1/go.mod h1:J8//BsAGTo3OC/vDLjMRFLW6q0WAaXvHnVc7ZmE8iUY= github.com/cosmos/ledger-go v0.9.2 h1:Nnao/dLwaVTk1Q5U9THldpUMMXU94BOTWPddSmVB6pI= github.com/cosmos/ledger-go v0.9.2/go.mod h1:oZJ2hHAZROdlHiwTg4t7kP+GKIIkBT+o6c9QWFanOyI= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= @@ -102,15 +128,31 @@ github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2 github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218= +github.com/dgraph-io/badger/v2 v2.0.3/go.mod h1:3KY8+bsP8wI0OEnQJAKpd4wIJW/Mm32yw2j/9FUVnIM= +github.com/dgraph-io/badger/v2 v2.2007.1/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE= +github.com/dgraph-io/badger/v2 v2.2007.2 h1:EjjK0KqwaFMlPin1ajhP943VPENHJdEz1KLIegjaI3k= +github.com/dgraph-io/badger/v2 v2.2007.2/go.mod h1:26P/7fbL4kUZVEVKLAKXkBXKOydDmM2p1e+NhhnBCAE= +github.com/dgraph-io/ristretto v0.0.2-0.20200115201040-8f368f2f2ab3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgraph-io/ristretto v0.0.3-0.20200630154024-f66de99634de/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgraph-io/ristretto v0.0.3 h1:jh22xisGBjrEVnRZ1DVTpBVQm0Xndu8sMl0CWDzSIBI= +github.com/dgraph-io/ristretto v0.0.3/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 h1:fAjc9m62+UWV/WAFKLNi6ZS0675eEUC9y3AlwSbQu1Y= +github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= -github.com/dvsekhvalnov/jose2go v0.0.0-20180829124132-7f401d37b68a h1:mq+R6XEM6lJX5VlLyZIrUSP8tSuJp82xTK89hvBwJbU= -github.com/dvsekhvalnov/jose2go v0.0.0-20180829124132-7f401d37b68a/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b h1:HBah4D48ypg3J7Np4N+HY/ZR76fx3HEUGxDU6Uk39oQ= +github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b/go.mod h1:7BvyPhdbLxMXIYTFPLsyJRFMsKmOZnQmzh6Gb+uquuM= github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= github.com/edsrzf/mmap-go v1.0.0/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M= +github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25 h1:2vLKys4RBU4pn2T/hjXMbvwTr1Cvy5THHrQkbeY9HRk= +github.com/enigmampc/btcutil v1.0.3-0.20200723161021-e2fb6adb2a25/go.mod h1:hTr8+TLQmkUkgcuh3mcr5fjrT9c64ZzsBCdCEC6UppY= github.com/envoyproxy/go-control-plane v0.6.9/go.mod h1:SBwIajubJHhxtWwsL9s8ss4safvEdbitLhGGK48rN6g= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -123,13 +165,19 @@ github.com/facebookgo/stack v0.0.0-20160209184415-751773369052/go.mod h1:UbMTZqL github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870 h1:E2s37DuLxFhQDg5gKsWoLBOB0n+ZW8s599zru8FJ2/Y= github.com/facebookgo/subset v0.0.0-20150612182917-8dac2c3c4870/go.mod h1:5tD+neXqOorC30/tWg0LCSkrqj/AR6gu8yY8/fpw1q0= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4= github.com/franela/goreq v0.0.0-20171204163338-bcd34c9993f8/go.mod h1:ZhphrRTfi2rbfLwlschooIH4+wKKDR4Pdxhh+TRoA20= -github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.10.0 h1:dXFJfIHVvUcpSgDOV+Ne6t7jXri8Tfv2uOLHUZ2XNuo= @@ -143,84 +191,107 @@ github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2 h1:ZpnhV/YsD2/4cESfV5+Hoeu/iUR3ruzNvZ+yQfO03a0= github.com/godbus/dbus v0.0.0-20190726142602-4481cbc300e2/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= +github.com/gogo/gateway v1.1.0 h1:u0SuhL9+Il+UbjM9VIE3ntfRujKbvVpFvNB4HbjeVQ0= +github.com/gogo/gateway v1.1.0/go.mod h1:S7rR8FRQyG3QFESeSv4l2WnsyzlCLG0CzBbUUo/mbic= github.com/gogo/googleapis v1.1.0/go.mod h1:gf4bu3Q80BeJ6H1S1vYPm8/ELATdvryBaNFGgqEef3s= -github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= -github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4= -github.com/gogo/protobuf v1.3.1 h1:DqDEcV5aeaTmdFBePNpYsp3FlcVH/2ISVVM9Qf8PSls= -github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= -github.com/golang/mock v1.3.1-0.20190508161146-9fa652df1129/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= -github.com/golang/mock v1.4.3 h1:GV+pQPG/EUUbkh47niozDcADz6go/dUwhVzdUQHIVRw= -github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.4 h1:l75CXGRSwbaYNpl/Z2X1XIIAMSCquvXgpVZDhwEIJsc= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.0/go.mod h1:Qd/q+1AKNOZr9uGQzbzCmRO6sUih6GTPZv6a1/R87v0= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= -github.com/golang/protobuf v1.4.0 h1:oOuy+ugB+P/kBdUnG5QaMXSIyJ1q38wWSojYCb3z5VQ= github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2 h1:+Z5KGCizgyZCbGh1KZqA0fcLLkwbsjIzS4aV2v7wJX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3 h1:JjCZWpVbqXDqFVmTfYWEVTMIYrL/NPdPSCHPJ0T/raM= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= -github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.2 h1:aeE13tS0IiQgFjYdoL8qN3K1N2bXXtI6Vi51/y7BpMw= +github.com/golang/snappy v0.0.2/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/btree v1.0.0 h1:0udJVsspx3VBr5FwtLhQQtuAsVc79tTq0ocGIPAU6qo= github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg= -github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= github.com/gorilla/mux v1.6.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= -github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= -github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/websocket v0.0.0-20170926233335-4201258b820c/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= github.com/grpc-ecosystem/go-grpc-middleware v1.0.1-0.20190118093823-f849b5445de4/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.1/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= +github.com/grpc-ecosystem/go-grpc-middleware v1.2.2/go.mod h1:EaizFBKfUKtMIF5iaDEhniwNedqGo9FuLFzppDr3uwI= github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= +github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= github.com/grpc-ecosystem/grpc-gateway v1.9.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/grpc-ecosystem/grpc-gateway v1.14.7/go.mod h1:oYZKL012gGh6LMyg/xA7Q2yq6j8bu0wa+9w14EEthWU= +github.com/grpc-ecosystem/grpc-gateway v1.15.2 h1:HC+hWRWf+v5zTMPyoaYTKIJih+4sd4XRWmj0qlG87Co= +github.com/grpc-ecosystem/grpc-gateway v1.15.2/go.mod h1:vO11I9oWA+KsxmfFQPhLnnIb1VDE24M+pdxZFiuZcA8= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c h1:6rhixN/i8ZofjG1Y75iExal34USq5p+wiN1tpie8IrU= github.com/gsterjov/go-libsecret v0.0.0-20161001094733-a6f4afe4910c/go.mod h1:NMPJylDgVpX0MLRlPy15sqSwOFv/U1GZ2m21JhFfek0= -github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f h1:8N8XWLZelZNibkhM1FuF+3Ad3YIbgirjdMiVA0eUkaM= github.com/gtank/merlin v0.1.1-0.20191105220539-8318aed1a79f/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= github.com/gtank/merlin v0.1.1 h1:eQ90iG7K9pOhtereWsmyRJ6RAwcP4tHTDBHXNg+u5is= github.com/gtank/merlin v0.1.1/go.mod h1:T86dnYJhcGOh5BjZFCJWTDeTK7XW8uE+E21Cy/bIQ+s= github.com/gtank/ristretto255 v0.1.2 h1:JEqUCPA1NvLq5DwYtuzigd7ss8fwbYay9fi4/5uMzcc= github.com/gtank/ristretto255 v0.1.2/go.mod h1:Ph5OpO6c7xKUGROZfWVLiJf9icMDwUeIvY4OmlYW69o= +github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q= github.com/hashicorp/consul/api v1.3.0/go.mod h1:MmDNSzIMUjNpY/mQ398R4bk2FnqQLoPndWW5VkKPlCE= +github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/consul/sdk v0.3.0/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-immutable-radix v1.0.0 h1:AKDB1HM5PWEA7i4nhcpwOrO2byshxBjXVn/J/3+z5/0= github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60= github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM= github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= +github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU= github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4= github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90= @@ -234,32 +305,38 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/jessevdk/go-flags v0.0.0-20141203071132-1679536dcc89/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmhodges/levigo v1.0.0 h1:q5EC36kV79HWeTBWsod3mG11EgStG3qArTKcvlksN1U= github.com/jmhodges/levigo v1.0.0/go.mod h1:Q6Qx+uH3RAqyK4rFQroq9RL7mdkABMcfhEI+nNuzMJQ= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/jpillora/backoff v1.0.0/go.mod h1:J/6gKK9jxlEcS3zixgDgUAsiuZ7yrSoa/FX5e0EB2j4= github.com/jrick/logrotate v1.0.0/go.mod h1:LNinyqDIJnpAur+b8yyulnQw/wDuN1+BYKlTRt3OuAQ= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.8/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d h1:Z+RDyXzjKE0i2sTjZ/b1uxiGtPhFy34Ou/Tk0qwN0kM= +github.com/keybase/go-keychain v0.0.0-20190712205309-48d3d31d256d/go.mod h1:JJNrCn9otv/2QP4D7SMJBgaleKpOf66PnW6F5WGNRIc= github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/kkdai/bstream v0.0.0-20161212061736-f391b8402d23/go.mod h1:J+Gs4SYgM6CZQHDETBtE9HaSEkGmuNXF86RwHhHUvq4= +github.com/kkdai/bstream v1.0.0/go.mod h1:FDnDOHt5Yx4p3FaHcioFT0QjDOtgUpvjeZqAs+NVZZA= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= @@ -270,8 +347,9 @@ github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-b github.com/lightstep/lightstep-tracer-go v0.18.1/go.mod h1:jlF1pusYV4pidLvZ+XD0UBX0ZE6WURAspgAczcDHrL4= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= -github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/magiconair/properties v1.8.4 h1:8KGKTcQQGm0Kv7vEbKFErAoAOFyyacLStRtQSeYtvkY= +github.com/magiconair/properties v1.8.4/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= @@ -283,8 +361,9 @@ github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5 github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643 h1:hLDRPB66XQT/8+wG9WsDpiCvZf1yKO7sz7scAjSlBa0= github.com/mimoo/StrobeGo v0.0.0-20181016162300-f8f6d4d2b643/go.mod h1:43+3pMjjKimDBf5Kr4ZFNGbLql1zKkbImw+fZbw3geM= -github.com/minio/highwayhash v1.0.0 h1:iMSDhgUILCr0TNm8LWlSjF8N0ZIj2qbO8WHp6Q/J2BA= github.com/minio/highwayhash v1.0.0/go.mod h1:xQboMTeM9nY9v/LlAOxFctujiv5+Aq2hR5dxBpaMbdc= +github.com/minio/highwayhash v1.0.1 h1:dZ6IIu8Z14VlC0VpfKofAhCy74wu/Qb5gcn52yWoz/0= +github.com/minio/highwayhash v1.0.1/go.mod h1:BQskDq+xkJ12lmlUUi7U0M5Swg3EWR+dLTk+kldvVxY= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= @@ -299,7 +378,10 @@ github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/mtibben/percent v0.2.1 h1:5gssi8Nqo8QU/r2pynCm+hBQHpkB/uNK7BJCFogWdzs= +github.com/mtibben/percent v0.2.1/go.mod h1:KG9uO+SZkUp+VkRHsCdYQV3XSZrrSpR3O9ibNBTZrns= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/nats-io/jwt v0.3.0/go.mod h1:fRYCDE99xlTsqUzISS1Bi75UBJ6ljOJQOAAu5VglpSg= github.com/nats-io/jwt v0.3.2/go.mod h1:/euKqTS1ZD+zzjYrY7pseZrTtWQSjujC7xjPc8wL6eU= github.com/nats-io/nats-server/v2 v2.1.2/go.mod h1:Afk+wRZqkMQs/p45uXdrVLuab3gwv3Z8C4HTBu8GD/k= @@ -307,17 +389,24 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/nxadm/tail v1.4.4 h1:DQuhQpB1tVlglWS2hLQ5OV6B5r8aGxSrPc5Qo6uTN78= +github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= -github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= -github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk= +github.com/onsi/ginkgo v1.14.0 h1:2mOpI4JVVPBN+WQRa0WKH2eXR+Ey+uK4n7Zj0aYpIQA= +github.com/onsi/ginkgo v1.14.0/go.mod h1:iSB4RoI2tjJc9BBv4NKIKWKya62Rps+oPG/Lv9klQyY= +github.com/onsi/gomega v1.4.1/go.mod h1:C1qb7wdrVGGVU+Z6iS04AVkA3Q65CEZX59MT0QO5uiA= github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= -github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= -github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= +github.com/onsi/gomega v1.10.1 h1:o0+MgICZLuZ7xjH7Vx6zS/zcu93/BEp1VwkIW1mEXCE= +github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= @@ -327,21 +416,25 @@ github.com/openzipkin-contrib/zipkin-go-opentracing v0.4.5/go.mod h1:/wsWhb9smxS github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= github.com/openzipkin/zipkin-go v0.2.1/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= github.com/openzipkin/zipkin-go v0.2.2/go.mod h1:NaW6tEwdmWMaCDZzg8sh+IBNOxHMPnhQw8ySjnjRyN4= -github.com/otiai10/copy v1.0.2 h1:DDNipYy6RkIkjMwy+AWzgKiNTyj2RUI9yEMeETEpVyc= -github.com/otiai10/copy v1.0.2/go.mod h1:c7RpqBkwMom4bYTSkLSym4VSJz/XtncWRAj/J4PEIMY= +github.com/otiai10/copy v1.2.0 h1:HvG945u96iNadPoG2/Ja2+AUJeW5YuFQMixq9yirC+k= +github.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw= github.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE= -github.com/otiai10/curr v0.0.0-20190513014714-f5a3d24e5776 h1:o59bHXu8Ejas8Kq6pjoVJQ9/neN66SM8AKh6wI42BBs= -github.com/otiai10/curr v0.0.0-20190513014714-f5a3d24e5776/go.mod h1:3HNVkVOU7vZeFXocWuvtcS0XSFLcf2XUSDHkq9t1jU4= -github.com/otiai10/mint v1.2.4/go.mod h1:d+b7n/0R3tdyUYYylALXpWQ/kTN+QobSq/4SRGBkR3M= -github.com/otiai10/mint v1.3.0 h1:Ady6MKVezQwHBkGzLFbrsywyp09Ah7rkmfjV3Bcr5uc= +github.com/otiai10/curr v1.0.0 h1:TJIWdbX0B+kpNagQrjgq8bCMrbhiuX73M2XwgtDMoOI= +github.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs= github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo= +github.com/otiai10/mint v1.3.1 h1:BCmzIS3n71sGfHB5NMNDB3lHYPz8fWSkCAErHed//qc= +github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc= github.com/pact-foundation/pact-go v1.0.4/go.mod h1:uExwJY4kCzNPcHRj+hCR/HBbOOIwwtUjcrb0b5/5kLM= github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= +github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= +github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= github.com/pborman/uuid v1.2.0/go.mod h1:X/NO0urCmaxf9VXbdlT7C2Yzkj2IKimNn4k+gtPdI/k= github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= -github.com/pelletier/go-toml v1.6.0 h1:aetoXYr0Tv7xRU/V4B4IZJ2QcbtMUFoNb3ORp7TzIK4= -github.com/pelletier/go-toml v1.6.0/go.mod h1:5N711Q9dKgbdkxHL+MEfF31hpT7l0S0s/t2kKREewys= +github.com/pelletier/go-toml v1.8.0 h1:Keo9qb7iRJs2voHvunFtuuYFsbWeOBh8/P9v/kVMFtw= +github.com/pelletier/go-toml v1.8.0/go.mod h1:D6yutnOGMveHEPV7VQOuvI/gXY61bv+9bAOTRnLElKs= github.com/performancecopilot/speed v3.0.0+incompatible/go.mod h1:/CLtqpZ5gBg1M9iaPbIdPPGyKcA8hKdoy6hAWba7Yac= +github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5 h1:q2e307iGHPdTGp0hoxKjt1H5pDo6utceo3dQVK3I5XQ= +github.com/petermattis/goid v0.0.0-20180202154549-b0b1615b78e5/go.mod h1:jvVRKCrJTQWu0XVbaOlby/2lO20uSCHEMzzplHXte1o= github.com/pierrec/lz4 v1.0.2-0.20190131084431-473cd7ce01a1/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -357,8 +450,11 @@ github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= -github.com/prometheus/client_golang v1.5.1 h1:bdHYieyGlH+6OLEk2YQha8THib30KP0/yD0YH9m6xcA= -github.com/prometheus/client_golang v1.5.1/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= +github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= +github.com/prometheus/client_golang v1.7.1 h1:NTGy1Ja9pByO+xAeH/qiWnLrKtr3hJPNjaVUwnjpdpA= +github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= +github.com/prometheus/client_golang v1.8.0 h1:zvJNkoCFAnYFNC24FV8nW4JdRJ3GIFcLbg65lL/JDcw= +github.com/prometheus/client_golang v1.8.0/go.mod h1:O9VU6huf47PktckDQfMTX0Y8tY0/7TSWwj+ITvv0TnM= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= @@ -371,31 +467,45 @@ github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y8 github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= -github.com/prometheus/common v0.9.1 h1:KOMtN28tlbam3/7ZKEYKHhKoJZYYj3gMH4uc62x7X7U= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= +github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= +github.com/prometheus/common v0.14.0 h1:RHRyE8UocrbjU+6UvRzwi6HjiDfxrrBU91TtbKzkGp4= +github.com/prometheus/common v0.14.0/go.mod h1:U+gB1OBLb1lF3O42bTCL+FK18tX9Oar16Clt/msog/s= github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= -github.com/prometheus/procfs v0.0.8 h1:+fpWZdT24pJBiqJdAwYBjPSk+5YmQzYNPYzQsdzLkt8= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= +github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= +github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= +github.com/prometheus/procfs v0.2.0 h1:wH4vA7pcjKuZzjF7lM8awk4fnuJO6idemZXoKnULUx4= +github.com/prometheus/procfs v0.2.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU= -github.com/rakyll/statik v0.1.6 h1:uICcfUXpgqtw2VopbIncslhAmE5hwc4g20TEyEENBNs= -github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs= +github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= +github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0 h1:MkV+77GLUNo5oJ0jf870itWm3D0Sjh7+Za9gazKc5LQ= github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/regen-network/cosmos-proto v0.3.0 h1:24dVpPrPi0GDoPVLesf2Ug98iK5QgVscPl0ga4Eoub0= +github.com/regen-network/cosmos-proto v0.3.0/go.mod h1:zuP2jVPHab6+IIyOx3nXHFN+euFNeS3W8XQkcdd4s7A= +github.com/regen-network/protobuf v1.3.2-alpha.regen.4 h1:c9jEnU+xm6vqyrQe3M94UFWqiXxRIKKnqBOh2EACmBE= +github.com/regen-network/protobuf v1.3.2-alpha.regen.4/go.mod h1:/J8/bR1T/NXyIdQDLUaq15LjNE83nRzkyrLAMcPewig= github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/sasha-s/go-deadlock v0.2.0 h1:lMqc+fUb7RrFS3gQLtoQsJ7/6TV/pAIFvBsqX73DK8Y= +github.com/sasha-s/go-deadlock v0.2.0/go.mod h1:StQn567HiB1fF2yJ44N9au7wOhrPS3iZqiDbRupzT10= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= @@ -405,15 +515,19 @@ github.com/snikch/goodman v0.0.0-20171125024755-10e37e294daa/go.mod h1:oJyF+mSPH github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.2.1/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/afero v1.2.2 h1:5jhuqJyZCZf2JRofRvN/nIFgIWNzPa3/Vz8mYylgbWc= github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= -github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng= +github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ= -github.com/spf13/cobra v1.0.0 h1:6m/oheQuQ13N9ks4hubMG6BnvwOeaJrqSPLahSnczz8= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.0.0/go.mod h1:/6GTrnGXV9HjY+aR4k0oJ5tcvakLuG6EuKReYlHNrgE= +github.com/spf13/cobra v1.1.0 h1:aq3wCKjTPmzcNWLVGnsFVN4rflK7Uzn10F8/aw8MhdQ= +github.com/spf13/cobra v1.1.0/go.mod h1:yk5b0mALVusDL5fMM6Rd1wgnoO5jUPhwsQ6LQAJTidQ= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= @@ -421,9 +535,11 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE= -github.com/spf13/viper v1.6.3 h1:pDDu1OyEDTKzpJwdq4TiuLyMsUgRa/BT5cn5O62NoHs= -github.com/spf13/viper v1.6.3/go.mod h1:jUMtyi0/lB5yZH/FjyGAoH7IMNrIhlBf6pXZmbMDvzw= +github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= +github.com/spf13/viper v1.7.1 h1:pM5oEahlgWv/WnHXpgbKz7iLIxRf65tye2Ci+XFK5sk= +github.com/spf13/viper v1.7.1/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= @@ -434,33 +550,35 @@ github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoH github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= -github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d h1:gZZadD8H+fF+n9CmNhYL1Y0dJB+kLOmKd7FbPJLeGHs= github.com/syndtr/goleveldb v1.0.1-0.20190923125748-758128399b1d/go.mod h1:9OrXJhf154huy1nPWmuSrkgjPUtUNhA+Zmy+6AESzuA= +github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca h1:Ld/zXl5t4+D69SiV4JoN7kkfvJdOWlPpfxrzxpLMoUk= +github.com/syndtr/goleveldb v1.0.1-0.20200815110645-5c35d600f0ca/go.mod h1:u2MKkTVTVJWe5D1rCvame8WqhBd88EuIwODJZ1VHCPM= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c h1:g+WoO5jjkqGAzHWCjJB1zZfXPIAaDpzXIEJ0eS6B5Ok= github.com/tecbot/gorocksdb v0.0.0-20191217155057-f0fad39f321c/go.mod h1:ahpPrc7HpcfEWDQRZEmnXMzHY03mLDYMCxeDzy46i+8= github.com/tendermint/btcd v0.1.1 h1:0VcxPfflS2zZ3RiOAHkBiFUcPvbtRj5O7zHmcJWHV7s= github.com/tendermint/btcd v0.1.1/go.mod h1:DC6/m53jtQzr/NFmMNEu0rxf18/ktVoVtMrnDD5pN+U= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15 h1:hqAk8riJvK4RMWx1aInLzndwxKalgi5rTqgfXxOxbEI= github.com/tendermint/crypto v0.0.0-20191022145703-50d29ede1e15/go.mod h1:z4YtwM70uOnk8h0pjJYlj3zdYwi9l03By6iAIF5j/Pk= -github.com/tendermint/go-amino v0.14.1/go.mod h1:i/UKE5Uocn+argJJBb12qTZsCDBcAYMbR92AaJVmKso= -github.com/tendermint/go-amino v0.15.1 h1:D2uk35eT4iTsvJd9jWIetzthE5C0/k2QmMFkCN+4JgQ= -github.com/tendermint/go-amino v0.15.1/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= -github.com/tendermint/iavl v0.14.0 h1:Jkff+IFrXxRWtH9Jn/ga/2cxNnzMTv58xEKgCJsKUBg= -github.com/tendermint/iavl v0.14.0/go.mod h1:QmfViflFiXzxKLQE4tAUuWQHq+RSuQFxablW5oJZ6sE= -github.com/tendermint/tendermint v0.33.5/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= -github.com/tendermint/tendermint v0.33.6 h1:W4UOsXY4ROJZ3TLLGVVv71VXD4WK2gJRb3gzeced+mg= -github.com/tendermint/tendermint v0.33.6/go.mod h1:0yUs9eIuuDq07nQql9BmI30FtYGcEC60Tu5JzB5IezM= -github.com/tendermint/tm-db v0.5.1 h1:H9HDq8UEA7Eeg13kdYckkgwwkQLBnJGgX4PgLJRhieY= +github.com/tendermint/go-amino v0.16.0 h1:GyhmgQKvqF82e2oZeuMSp9JTN0N09emoSZlb2lyGa2E= +github.com/tendermint/go-amino v0.16.0/go.mod h1:TQU0M1i/ImAo+tYpZi73AU3V/dKeCoMC9Sphe2ZwGME= +github.com/tendermint/tendermint v0.34.0-rc3/go.mod h1:BoHcEpjfpBHc1Be7RQz3AHaXFNObcDG7SNHCev6Or4g= +github.com/tendermint/tendermint v0.34.0-rc4/go.mod h1:yotsojf2C1QBOw4dZrTcxbyxmPUrT4hNuOQWX9XUwB4= +github.com/tendermint/tendermint v0.34.0-rc5 h1:2bnQfWyOMfTCbol5pwB8CgM2nxi6/Kz6zqlS6Udm/Cg= +github.com/tendermint/tendermint v0.34.0-rc5/go.mod h1:yotsojf2C1QBOw4dZrTcxbyxmPUrT4hNuOQWX9XUwB4= github.com/tendermint/tm-db v0.5.1/go.mod h1:g92zWjHpCYlEvQXvy9M168Su8V1IBEeawpXVVBaK4f4= +github.com/tendermint/tm-db v0.6.1/go.mod h1:m3x9kRP4UFd7JODJL0yBAZqE7wTw+S37uAE90cTx7OA= +github.com/tendermint/tm-db v0.6.2 h1:DOn8jwCdjJblrCFJbtonEIPD1IuJWpbRUUdR8GWE4RM= +github.com/tendermint/tm-db v0.6.2/go.mod h1:GYtQ67SUvATOcoY8/+x6ylk8Qo02BQyLrAs+yAcLvGI= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= +github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= @@ -469,11 +587,13 @@ github.com/zondax/hid v0.9.0 h1:eiT3P6vNxAEVxXMw66eZUAAnU2zD33JBkfG/EnfAKl8= github.com/zondax/hid v0.9.0/go.mod h1:l5wttcP0jwtdLjqjMMWFVEE7d1zO0jvSPA9OPZxWpEM= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/bbolt v1.3.4 h1:hi1bXHMVrlQh6WwxAy+qZCV/SYIlqo+Ushwdpa4tAKg= -go.etcd.io/bbolt v1.3.4/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= +go.etcd.io/bbolt v1.3.5 h1:XAzx9gjCb0Rxj7EoqcClPD1d5ZBxZJk0jbuoPHenBt0= +go.etcd.io/bbolt v1.3.5/go.mod h1:G5EMThwa9y8QZGBClrRx5EY+Yw9kAhnjy3bSjsnlVTQ= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= @@ -486,24 +606,44 @@ go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= golang.org/x/crypto v0.0.0-20170930174604-9419663f5a44/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 h1:ULYEB3JvPRE/IfO+9uO7vKV/xzVTO7XPAwm8xbf4w2g= golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200115085410-6d4e4cb37c7d/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200406173513-056763e48d71/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79 h1:IaQbIIB2X/Mp/DKctl6ROxz1KyMlKp4uyvL6+kQ7C88= -golang.org/x/crypto v0.0.0-20200429183012-4b2356b1ed79/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200709230013-948cd5f35899/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a h1:vclmkQCjlDX5OydZ9wv8rBCcS0QyQY66Mpf/7BZbInM= +golang.org/x/crypto v0.0.0-20200820211705-5c72a883971a/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee h1:4yd7jl+vXjalO5ztz6Vc1VADv+S/80LGJmyl1ROJ2AI= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20200331195152-e8c3332aa8e5/go.mod h1:4M0jN8W1tt0AVLNr8HDosyJCDCDuyL9N9+3m7wDWgKw= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/net v0.0.0-20180719180050-a680a1efc54d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -516,16 +656,26 @@ golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73r golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= -golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e h1:3G+cUijn7XD+S4eJFddp53Pv7+slrESplyjG25HgL+k= +golang.org/x/net v0.0.0-20191002035440-2ec189313ef0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200421231249-e086a090c8fd/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200813134508-3edf25e44fcc/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200930145003-4acb6c075d10 h1:YfxMZzv3PjGonQYNUaeU2+DhAdqOxerQ30JFB6WgAXo= +golang.org/x/net v0.0.0-20200930145003-4acb6c075d10/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -540,87 +690,148 @@ golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190130150945-aca44879d564/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190712062909-fae7ac547cb7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191220142924-d4481acd189f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980 h1:OjiUf46hAmXblsZdnoSXsEUSKU8r1UEzcL5RVZ4gO9Y= -golang.org/x/sys v0.0.0-20200602225109-6fdc65e7d980/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/sys v0.0.0-20200420163511-1957bb5e6d1f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200519105757-fe76b779f299/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200625212154-ddb9806d33ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed h1:J22ig1FUekjjkmZUM7pTKixYm8DvrYsvrBZdunYeIuQ= +golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211 h1:9UQO31fZ+0aKQOFldThf7BKPMJTiBfWycGh/u3UoO88= +golang.org/x/sys v0.0.0-20201015000850-e3ed0017c211/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= -golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200110213125-a7a6caa82ab2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.2.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20180831171423-11092d34479b/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= google.golang.org/genproto v0.0.0-20190530194941-fb225487d101/go.mod h1:z3L6/3dTEVtUr6QSP8miRzeRqwQOioJ9I66odjN4I7s= -google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200324203455-a04cca1dde73/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987 h1:PDIOdWxZ8eRizhKa1AAvY53xsvLB1cWorMjslvY3VA8= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201014134559-03b6142f0dc9 h1:fG84H9C3EXfuDlzkG+VEPDYHHExklP6scH1QZ5gQTqU= +google.golang.org/genproto v0.0.0-20201014134559-03b6142f0dc9/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.19.1/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.0/go.mod h1:chYK+tFQF0nDUGJgXMSgLCQk3phJEuONr2DCgLDdAQM= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.23.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= -google.golang.org/grpc v1.28.0 h1:bO/TA4OxCOummhSf10siHuG7vJOiwh7SpRpFZDkOgl4= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.28.1/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= -google.golang.org/grpc v1.30.0 h1:M5a8xTlYTxwMn5ZFkwhRabsygDY5G8TYLyQDBxJNAxE= -google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.32.0 h1:zWTV+LMdc3kaiJMSTOFz2UgSBgx8RNQoTGiZu3fR9S0= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.0 h1:IBKSUNL2uBS2DkJBncPP+TwT0sp9tgA8A75NjHt6umg= +google.golang.org/grpc v1.33.0/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= -google.golang.org/protobuf v1.21.0 h1:qdOKuR/EIArgaWNjetjgTzgVTAZ+S/WXVrq9HW9zimw= google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b h1:QRR6H1YWRnHb4Y/HeNFCTJLFVxaq6wH4YuVdsUOr75U= +gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/cheggaaa/pb.v1 v1.0.25/go.mod h1:V/YB90LKu/1FcN3WVnfiiE5oMCibMjukxqG/qStrOgw= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno= @@ -632,9 +843,9 @@ gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRN gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -642,9 +853,10 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= -rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= -rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1:hI742Nqp5OhwiqlzhgfbWU4mW4yO10fP+LoT9WOswdU= diff --git a/lcd_test/helpers.go b/lcd_test/helpers.go deleted file mode 100644 index 0517884889..0000000000 --- a/lcd_test/helpers.go +++ /dev/null @@ -1,512 +0,0 @@ -package lcdtest - -import ( - "bytes" - "fmt" - "io/ioutil" - "net" - "os" - "path/filepath" - "sort" - "strings" - - "github.com/pkg/errors" - "github.com/spf13/viper" - - "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/lcd" - "github.com/cosmos/cosmos-sdk/codec" - crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/server" - storetypes "github.com/cosmos/cosmos-sdk/store/types" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" - "github.com/cosmos/cosmos-sdk/x/crisis" - distr "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/genutil" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" - - tmcfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/crypto/secp256k1" - "github.com/tendermint/tendermint/libs/cli" - "github.com/tendermint/tendermint/libs/log" - nm "github.com/tendermint/tendermint/node" - "github.com/tendermint/tendermint/p2p" - pvm "github.com/tendermint/tendermint/privval" - "github.com/tendermint/tendermint/proxy" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - tmrpc "github.com/tendermint/tendermint/rpc/jsonrpc/server" - tmtypes "github.com/tendermint/tendermint/types" - dbm "github.com/tendermint/tm-db" - - "github.com/CosmWasm/wasmd/app" - "github.com/CosmWasm/wasmd/x/wasm" -) - -// TODO: Make InitializeTestLCD safe to call in multiple tests at the same time - -// InitializeLCD starts Tendermint and the LCD in process, listening on -// their respective sockets where nValidators is the total number of validators -// and initAddrs are the accounts to initialize with some stake tokens. It -// returns a cleanup function, a set of validator public keys, and a port. -func InitializeLCD(nValidators int, initAddrs []sdk.AccAddress, minting bool, portExt ...string) ( - cleanup func(), valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, port string, err error) { - - config, err := GetConfig() - if err != nil { - return - } - config.Consensus.TimeoutCommit = 100 - config.Consensus.SkipTimeoutCommit = false - config.TxIndex.IndexAllKeys = true - - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) - logger = log.NewFilter(logger, log.AllowError()) - - db := dbm.NewMemDB() - gapp := app.NewWasmApp(logger, db, nil, true, 0, wasm.EnableAllProposals, nil, baseapp.SetPruning(storetypes.PruneNothing)) - cdc = app.MakeCodec() - - genDoc, valConsPubKeys, valOperAddrs, privVal, err := defaultGenesis(config, nValidators, initAddrs, minting) - if err != nil { - return - } - - var listenAddr string - - if len(portExt) == 0 { - listenAddr, port, err = server.FreeTCPAddr() - if err != nil { - return - } - } else { - listenAddr = fmt.Sprintf("tcp://0.0.0.0:%s", portExt[0]) - port = portExt[0] - } - - // XXX: Need to set this so LCD knows the tendermint node address! - viper.Set(flags.FlagNode, config.RPC.ListenAddress) - viper.Set(flags.FlagChainID, genDoc.ChainID) - // TODO Set to false once the upstream Tendermint proof verification issue is fixed. - viper.Set(flags.FlagTrustNode, true) - - node, err := startTM(config, logger, genDoc, privVal, gapp) - if err != nil { - return - } - - tests.WaitForNextHeightTM(tests.ExtractPortFromAddress(config.RPC.ListenAddress)) - - lcdInstance, err := startLCD(logger, listenAddr, cdc) - if err != nil { - return - } - - tests.WaitForLCDStart(port) - tests.WaitForHeight(1, port) - - cleanup = func() { - logger.Debug("cleaning up LCD initialization") - err = node.Stop() - if err != nil { - logger.Error(err.Error()) - } - - node.Wait() - err = lcdInstance.Close() - if err != nil { - logger.Error(err.Error()) - } - } - - return cleanup, valConsPubKeys, valOperAddrs, port, err -} - -func defaultGenesis(config *tmcfg.Config, nValidators int, initAddrs []sdk.AccAddress, minting bool) ( - genDoc *tmtypes.GenesisDoc, valConsPubKeys []crypto.PubKey, valOperAddrs []sdk.ValAddress, privVal *pvm.FilePV, err error) { - privVal = pvm.LoadOrGenFilePV(config.PrivValidatorKeyFile(), - config.PrivValidatorStateFile()) - privVal.Reset() - - if nValidators < 1 { - err = errors.New("initializeLCD must use at least one validator") - return - } - - genesisFile := config.GenesisFile() - genDoc, err = tmtypes.GenesisDocFromFile(genesisFile) - if err != nil { - return - } - genDoc.Validators = nil - err = genDoc.SaveAs(genesisFile) - if err != nil { - return - } - - // append any additional (non-proposing) validators - //nolint:prealloc - var ( - genTxs []auth.StdTx - genAccounts []authexported.GenesisAccount - ) - totalSupply := sdk.ZeroInt() - - for i := 0; i < nValidators; i++ { - operPrivKey := secp256k1.GenPrivKey() - operAddr := operPrivKey.PubKey().Address() - pubKey, _ := privVal.GetPubKey() - - power := int64(100) - if i > 0 { - pubKey = ed25519.GenPrivKey().PubKey() - power = 1 - } - - startTokens := sdk.TokensFromConsensusPower(power) - - msg := staking.NewMsgCreateValidator( - sdk.ValAddress(operAddr), - pubKey, - sdk.NewCoin(sdk.DefaultBondDenom, startTokens), - staking.NewDescription(fmt.Sprintf("validator-%d", i+1), "", "", "", ""), - staking.NewCommissionRates(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - sdk.OneInt(), - ) - - stdSignMsg := auth.StdSignMsg{ - ChainID: genDoc.ChainID, - Msgs: []sdk.Msg{msg}, - } - - var sig []byte - sig, err = operPrivKey.Sign(stdSignMsg.Bytes()) - if err != nil { - return - } - - transaction := auth.NewStdTx([]sdk.Msg{msg}, auth.StdFee{}, []auth.StdSignature{{Signature: sig, PubKey: operPrivKey.PubKey()}}, "") - genTxs = append(genTxs, transaction) - valConsPubKeys = append(valConsPubKeys, pubKey) - valOperAddrs = append(valOperAddrs, sdk.ValAddress(operAddr)) - - account := auth.NewBaseAccountWithAddress(sdk.AccAddress(operAddr)) - accTokens := sdk.TokensFromConsensusPower(150) - totalSupply = totalSupply.Add(accTokens) - - account.Coins = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, accTokens)) - genAccounts = append(genAccounts, &account) - } - - genesisState := app.NewDefaultGenesisState() - genDoc.AppState, err = cdc.MarshalJSON(genesisState) - if err != nil { - return - } - - genesisState, err = genutil.SetGenTxsInAppGenesisState(cdc, genesisState, genTxs) - if err != nil { - return - } - - // add some tokens to init accounts - for _, addr := range initAddrs { - accAuth := auth.NewBaseAccountWithAddress(addr) - accTokens := sdk.TokensFromConsensusPower(100) - accAuth.Coins = sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, accTokens)} - totalSupply = totalSupply.Add(accTokens) - - genAccounts = append(genAccounts, &accAuth) - } - - // auth genesis state: params and genesis accounts - authDataBz := genesisState[auth.ModuleName] - var authGenState auth.GenesisState - cdc.MustUnmarshalJSON(authDataBz, &authGenState) - authGenState.Accounts = genAccounts - genesisState[auth.ModuleName] = cdc.MustMarshalJSON(authGenState) - - stakingDataBz := genesisState[staking.ModuleName] - var stakingData staking.GenesisState - cdc.MustUnmarshalJSON(stakingDataBz, &stakingData) - genesisState[staking.ModuleName] = cdc.MustMarshalJSON(stakingData) - - // distr data - distrDataBz := genesisState[distr.ModuleName] - var distrData distr.GenesisState - cdc.MustUnmarshalJSON(distrDataBz, &distrData) - - commPoolAmt := sdk.NewInt(10) - distrData.FeePool.CommunityPool = sdk.DecCoins{sdk.NewDecCoin(sdk.DefaultBondDenom, commPoolAmt)} - distrDataBz = cdc.MustMarshalJSON(distrData) - genesisState[distr.ModuleName] = distrDataBz - - // supply data - supplyDataBz := genesisState[supply.ModuleName] - var supplyData supply.GenesisState - cdc.MustUnmarshalJSON(supplyDataBz, &supplyData) - - supplyData.Supply = sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, totalSupply.Add(commPoolAmt))) - supplyDataBz = cdc.MustMarshalJSON(supplyData) - genesisState[supply.ModuleName] = supplyDataBz - - // mint genesis (none set within genesisState) - mintData := mint.DefaultGenesisState() - inflationMin := sdk.ZeroDec() - if minting { - inflationMin = sdk.MustNewDecFromStr("0.9") - mintData.Params.InflationMax = sdk.MustNewDecFromStr("1.0") - } else { - mintData.Params.InflationMax = inflationMin - } - mintData.Minter.Inflation = inflationMin - mintData.Params.InflationMin = inflationMin - mintDataBz := cdc.MustMarshalJSON(mintData) - genesisState[mint.ModuleName] = mintDataBz - - // initialize crisis data - crisisDataBz := genesisState[crisis.ModuleName] - var crisisData crisis.GenesisState - cdc.MustUnmarshalJSON(crisisDataBz, &crisisData) - crisisData.ConstantFee = sdk.NewInt64Coin(sdk.DefaultBondDenom, 1000) - crisisDataBz = cdc.MustMarshalJSON(crisisData) - genesisState[crisis.ModuleName] = crisisDataBz - - //// double check inflation is set according to the minting boolean flag - if minting { - if !(mintData.Params.InflationMax.Equal(sdk.MustNewDecFromStr("1.0")) && - mintData.Minter.Inflation.Equal(sdk.MustNewDecFromStr("0.9")) && - mintData.Params.InflationMin.Equal(sdk.MustNewDecFromStr("0.9"))) { - err = errors.New("mint parameters does not correspond to their defaults") - return - } - } else { - if !(mintData.Params.InflationMax.Equal(sdk.ZeroDec()) && - mintData.Minter.Inflation.Equal(sdk.ZeroDec()) && - mintData.Params.InflationMin.Equal(sdk.ZeroDec())) { - err = errors.New("mint parameters not equal to decimal 0") - return - } - } - - appState, err := codec.MarshalJSONIndent(cdc, genesisState) - if err != nil { - return - } - - genDoc.AppState = appState - return genDoc, valConsPubKeys, valOperAddrs, privVal, err -} - -// startTM creates and starts an in-process Tendermint node with memDB and -// in-process ABCI application. It returns the new node or any error that -// occurred. -// -// TODO: Clean up the WAL dir or enable it to be not persistent! -func startTM( - tmcfg *tmcfg.Config, logger log.Logger, genDoc *tmtypes.GenesisDoc, - privVal tmtypes.PrivValidator, app *app.WasmApp, -) (*nm.Node, error) { - - genDocProvider := func() (*tmtypes.GenesisDoc, error) { return genDoc, nil } - dbProvider := func(*nm.DBContext) (dbm.DB, error) { return dbm.NewMemDB(), nil } - nodeKey, err := p2p.LoadOrGenNodeKey(tmcfg.NodeKeyFile()) - if err != nil { - return nil, err - } - node, err := nm.NewNode( - tmcfg, - privVal, - nodeKey, - proxy.NewLocalClientCreator(app), - genDocProvider, - dbProvider, - nm.DefaultMetricsProvider(tmcfg.Instrumentation), - logger.With("module", "node"), - ) - if err != nil { - return nil, err - } - - err = node.Start() - if err != nil { - return nil, err - } - - tests.WaitForRPC(tmcfg.RPC.ListenAddress) - logger.Info("Tendermint running!") - - return node, err -} - -// startLCD starts the LCD. -func startLCD(logger log.Logger, listenAddr string, cdc *codec.Codec) (net.Listener, error) { - rs := lcd.NewRestServer(cdc) - registerRoutes(rs) - listener, err := tmrpc.Listen(listenAddr, tmrpc.DefaultConfig()) - if err != nil { - return nil, err - } - go tmrpc.Serve(listener, rs.Mux, logger, tmrpc.DefaultConfig()) //nolint:errcheck - return listener, nil -} - -// NOTE: If making updates here also update cmd/gaia/cmd/wasmcli/main.go -func registerRoutes(rs *lcd.RestServer) { - client.RegisterRoutes(rs.CliCtx, rs.Mux) - authrest.RegisterTxRoutes(rs.CliCtx, rs.Mux) - app.ModuleBasics.RegisterRESTRoutes(rs.CliCtx, rs.Mux) -} - -var cdc = codec.New() - -func init() { - ctypes.RegisterAmino(cdc) -} - -// CreateAddr adds an address to the key store and returns an address and seed. -// It also requires that the key could be created. -func CreateAddr(name string, kb crkeys.Keybase) (sdk.AccAddress, string, error) { - var ( - err error - info crkeys.Info - seed string - ) - info, seed, err = kb.CreateMnemonic(name, crkeys.English, keys.DefaultKeyPass, crkeys.Secp256k1) - if err != nil { - return nil, "", err - } - return sdk.AccAddress(info.GetPubKey().Address()), seed, err -} - -// CreateAddrs adds multiple address to the key store and returns the addresses and associated seeds in lexographical order by address. -// It also requires that the keys could be created. -func CreateAddrs(kb crkeys.Keybase, numAddrs int) (addrs []sdk.AccAddress, seeds, names []string, errs []error) { - var ( - err error - info crkeys.Info - seed string - ) - - addrSeeds := AddrSeedSlice{} - - for i := 0; i < numAddrs; i++ { - name := fmt.Sprintf("test%d", i) - info, seed, err = kb.CreateMnemonic(name, crkeys.English, keys.DefaultKeyPass, crkeys.Secp256k1) - if err != nil { - errs = append(errs, err) - } - addrSeeds = append(addrSeeds, AddrSeed{Address: sdk.AccAddress(info.GetPubKey().Address()), Seed: seed, Name: name}) - } - if len(errs) > 0 { - return - } - - sort.Sort(addrSeeds) - - for i := range addrSeeds { - addrs = append(addrs, addrSeeds[i].Address) - seeds = append(seeds, addrSeeds[i].Seed) - names = append(names, addrSeeds[i].Name) - } - - return addrs, seeds, names, errs -} - -// AddrSeed combines an Address with the mnemonic of the private key to that address -type AddrSeed struct { - Address sdk.AccAddress - Seed string - Name string -} - -// AddrSeedSlice implements `Interface` in sort package. -type AddrSeedSlice []AddrSeed - -func (b AddrSeedSlice) Len() int { - return len(b) -} - -// Less sorts lexicographically by Address -func (b AddrSeedSlice) Less(i, j int) bool { - // bytes package already implements Comparable for []byte. - switch bytes.Compare(b[i].Address.Bytes(), b[j].Address.Bytes()) { - case -1: - return true - case 0, 1: - return false - default: - panic("not fail-able with `bytes.Comparable` bounded [-1, 1].") - } -} - -func (b AddrSeedSlice) Swap(i, j int) { - b[j], b[i] = b[i], b[j] -} - -// InitClientHome initialises client home dir. -func InitClientHome(dir string) string { - var err error - if dir == "" { - dir, err = ioutil.TempDir("", "lcd_test") - if err != nil { - panic(err) - } - } - // TODO: this should be set in NewRestServer - // and pass down the CLIContext to achieve - // parallelism. - viper.Set(cli.HomeFlag, dir) - return dir -} - -// makePathname creates a unique pathname for each test. -func makePathname() (string, error) { - p, err := os.Getwd() - if err != nil { - return "", err - } - - sep := string(filepath.Separator) - return strings.Replace(p, sep, "_", -1), nil -} - -// GetConfig returns a Tendermint config for the test cases. -func GetConfig() (*tmcfg.Config, error) { - pathname, err := makePathname() - if err != nil { - return nil, err - } - config := tmcfg.ResetTestRoot(pathname) - - tmAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err - } - - rcpAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err - } - - grpcAddr, _, err := server.FreeTCPAddr() - if err != nil { - return nil, err - } - - config.P2P.ListenAddress = tmAddr - config.RPC.ListenAddress = rcpAddr - config.RPC.GRPCListenAddress = grpcAddr - - return config, nil -} diff --git a/lcd_test/helpers_test.go b/lcd_test/helpers_test.go deleted file mode 100644 index 36e007c9b2..0000000000 --- a/lcd_test/helpers_test.go +++ /dev/null @@ -1,1125 +0,0 @@ -//nolint:unused,deadcode,bodyclose -package lcdtest - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - clientkeys "github.com/cosmos/cosmos-sdk/client/keys" - "github.com/cosmos/cosmos-sdk/client/rpc" - "github.com/cosmos/cosmos-sdk/crypto/keys" - crkeys "github.com/cosmos/cosmos-sdk/crypto/keys" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth" - authrest "github.com/cosmos/cosmos-sdk/x/auth/client/rest" - authcutils "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - authexported "github.com/cosmos/cosmos-sdk/x/auth/exported" - bankrest "github.com/cosmos/cosmos-sdk/x/bank/client/rest" - distrrest "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" - "github.com/cosmos/cosmos-sdk/x/gov" - govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" - gcutils "github.com/cosmos/cosmos-sdk/x/gov/client/utils" - paramscutils "github.com/cosmos/cosmos-sdk/x/params/client/utils" - "github.com/cosmos/cosmos-sdk/x/slashing" - slashingrest "github.com/cosmos/cosmos-sdk/x/slashing/client/rest" - "github.com/cosmos/cosmos-sdk/x/staking" - stakingrest "github.com/cosmos/cosmos-sdk/x/staking/client/rest" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - ctypes "github.com/tendermint/tendermint/rpc/core/types" -) - -// Request makes a test LCD test request. It returns a response object and a -// stringified response body. -func Request(t *testing.T, port, method, path string, payload []byte) (*http.Response, string) { - var ( - err error - res *http.Response - ) - url := fmt.Sprintf("http://localhost:%v%v", port, path) - fmt.Printf("REQUEST %s %s\n", method, url) - - req, err := http.NewRequest(method, url, bytes.NewBuffer(payload)) - require.Nil(t, err) - - res, err = http.DefaultClient.Do(req) - require.Nil(t, err) - - output, err := ioutil.ReadAll(res.Body) - res.Body.Close() - require.Nil(t, err) - - return res, string(output) -} - -// ---------------------------------------------------------------------- -// ICS 0 - Tendermint -// ---------------------------------------------------------------------- -// GET /node_info The properties of the connected node -func getNodeInfo(t *testing.T, port string) rpc.NodeInfoResponse { - res, body := Request(t, port, "GET", "/node_info", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var nodeInfo rpc.NodeInfoResponse - err := cdc.UnmarshalJSON([]byte(body), &nodeInfo) - require.Nil(t, err, "failed parse node info") - - require.NotEqual(t, rpc.NodeInfoResponse{}, nodeInfo, "res: %v", res) - return nodeInfo -} - -// GET /syncing Syncing state of node -func getSyncStatus(t *testing.T, port string, syncing bool) { - res, body := Request(t, port, "GET", "/syncing", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var syncResp rpc.SyncingResponse - err := cdc.UnmarshalJSON([]byte(body), &syncResp) - require.Nil(t, err, "failed parse syncing info") - - require.Equal(t, syncResp.Syncing, syncing) -} - -// GET /blocks/latest Get the latest block -// GET /blocks/{height} Get a block at a certain height -func getBlock(t *testing.T, port string, height int, expectFail bool) ctypes.ResultBlock { - var url string - if height > 0 { - url = fmt.Sprintf("/blocks/%d", height) - } else { - url = "/blocks/latest" - } - var resultBlock ctypes.ResultBlock - - res, body := Request(t, port, "GET", url, nil) - if expectFail { - require.Equal(t, http.StatusNotFound, res.StatusCode, body) - return resultBlock - } - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &resultBlock) - require.Nil(t, err, "Couldn't parse block") - - require.NotEqual(t, ctypes.ResultBlock{}, resultBlock) - return resultBlock -} - -func extractResultFromResponse(t *testing.T, body []byte) []byte { - var resp rest.ResponseWithHeight - require.NoError(t, cdc.UnmarshalJSON(body, &resp)) - - return resp.Result -} - -// GET /validatorsets/{height} Get a validator set a certain height -// GET /validatorsets/latest Get the latest validator set -func getValidatorSets(t *testing.T, port string, height int, expectFail bool) rpc.ResultValidatorsOutput { - var url string - if height > 0 { - url = fmt.Sprintf("/validatorsets/%d", height) - } else { - url = "/validatorsets/latest" - } - - var resultVals rpc.ResultValidatorsOutput - res, body := Request(t, port, "GET", url, nil) - - if expectFail { - require.Equal(t, http.StatusNotFound, res.StatusCode, body) - return resultVals - } - - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &resultVals) - require.Nil(t, err, "Couldn't parse validator set") - - require.NotEqual(t, rpc.ResultValidatorsOutput{}, resultVals) - return resultVals -} - -// GET /txs/{hash} get tx by hash -func getTransaction(t *testing.T, port string, hash string) sdk.TxResponse { - var tx sdk.TxResponse - res, body := getTransactionRequest(t, port, hash) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &tx) - require.NoError(t, err) - - return tx -} - -func getTransactionRequest(t *testing.T, port, hash string) (*http.Response, string) { - return Request(t, port, "GET", fmt.Sprintf("/txs/%s", hash), nil) -} - -// POST /txs broadcast txs - -// GET /txs search transactions -func getTransactions(t *testing.T, port string, events ...string) *sdk.SearchTxsResult { - var txs []sdk.TxResponse - result := sdk.NewSearchTxsResult(0, 0, 1, 30, txs) - if len(events) == 0 { - return &result - } - - queryStr := strings.Join(events, "&") - res, body := Request(t, port, "GET", fmt.Sprintf("/txs?%s", queryStr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err := cdc.UnmarshalJSON([]byte(body), &result) - require.NoError(t, err) - - return &result -} - -// ---------------------------------------------------------------------- -// ICS 1 - Keys -// ---------------------------------------------------------------------- -// GET /keys List of accounts stored locally -func getKeys(t *testing.T, port string) []keys.KeyOutput { - res, body := Request(t, port, "GET", "/keys", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var m []keys.KeyOutput - err := cdc.UnmarshalJSON([]byte(body), &m) - require.Nil(t, err) - - return m -} - -// POST /keys Create a new account locally -func doKeysPost(t *testing.T, port, name, password, mnemonic string, account int, index int) keys.KeyOutput { - pk := clientkeys.NewAddNewKey(name, password, mnemonic, account, index) - req, err := cdc.MarshalJSON(pk) - require.NoError(t, err) - - res, body := Request(t, port, "POST", "/keys", req) - - require.Equal(t, http.StatusOK, res.StatusCode, body) - var resp keys.KeyOutput - err = cdc.UnmarshalJSON([]byte(body), &resp) - require.Nil(t, err, body) - - return resp -} - -// GET /auth/accounts/{address} Get the account information on blockchain -func getAccount(t *testing.T, port string, addr sdk.AccAddress) (acc authexported.Account) { - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", addr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Nil(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &acc)) - - return acc -} - -// ---------------------------------------------------------------------- -// ICS 20 - Tokens -// ---------------------------------------------------------------------- - -// POST /tx/broadcast Send a signed Tx -func doBroadcast(t *testing.T, port string, tx auth.StdTx) (*http.Response, string) { - txReq := authrest.BroadcastReq{Tx: tx, Mode: "block"} - - req, err := cdc.MarshalJSON(txReq) - require.Nil(t, err) - - return Request(t, port, "POST", "/txs", req) -} - -// doTransfer performs a balance transfer with auto gas calculation. It also signs -// the tx and broadcasts it. -func doTransfer( - t *testing.T, port, name, memo string, addr sdk.AccAddress, fees sdk.Coins, - kb crkeys.Keybase, -) (sdk.AccAddress, sdk.TxResponse) { - - resp, body, recvAddr := doTransferWithGas(t, port, name, memo, addr, "", 1.0, false, true, fees, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err := cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return recvAddr, txResp -} - -// doTransferWithGas performs a balance transfer with a specified gas value. The -// broadcast parameter determines if the tx should only be generated or also -// signed and broadcasted. The sending account's number and sequence are -// determined prior to generating the tx. -func doTransferWithGas( - t *testing.T, port, name, memo string, addr sdk.AccAddress, - gas string, gasAdjustment float64, simulate, broadcast bool, fees sdk.Coins, - kb crkeys.Keybase, -) (resp *http.Response, body string, receiveAddr sdk.AccAddress) { - - // create receive address - kb2 := crkeys.NewInMemory() - - receiveInfo, _, err := kb2.CreateMnemonic( - "receive_address", crkeys.English, clientkeys.DefaultKeyPass, crkeys.SigningAlgo("secp256k1"), - ) - require.Nil(t, err) - - receiveAddr = sdk.AccAddress(receiveInfo.GetPubKey().Address()) - acc := getAccount(t, port, addr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - - from := addr.String() - baseReq := rest.NewBaseReq( - from, memo, chainID, gas, fmt.Sprintf("%f", gasAdjustment), accnum, sequence, fees, nil, simulate, - ) - - sr := bankrest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(sr) - require.NoError(t, err) - - // generate tx - resp, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers", receiveAddr), req) - if !broadcast { - return resp, body, receiveAddr - } - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, gasAdjustment, simulate, kb) - return resp, body, receiveAddr -} - -// doTransferWithGasAccAuto is similar to doTransferWithGas except that it -// automatically determines the account's number and sequence when generating the -// tx. -func doTransferWithGasAccAuto( - t *testing.T, port, name, memo string, addr sdk.AccAddress, - gas string, gasAdjustment float64, simulate, broadcast bool, fees sdk.Coins, - kb crkeys.Keybase, -) (resp *http.Response, body string, receiveAddr sdk.AccAddress) { - - // create receive address - kb2 := crkeys.NewInMemory() - acc := getAccount(t, port, addr) - - receiveInfo, _, err := kb2.CreateMnemonic( - "receive_address", crkeys.English, clientkeys.DefaultKeyPass, crkeys.SigningAlgo("secp256k1"), - ) - require.Nil(t, err) - - receiveAddr = sdk.AccAddress(receiveInfo.GetPubKey().Address()) - chainID := viper.GetString(flags.FlagChainID) - - from := addr.String() - baseReq := rest.NewBaseReq( - from, memo, chainID, gas, fmt.Sprintf("%f", gasAdjustment), 0, 0, fees, nil, simulate, - ) - - sr := bankrest.SendReq{ - Amount: sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 1)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(sr) - require.NoError(t, err) - - resp, body = Request(t, port, "POST", fmt.Sprintf("/bank/accounts/%s/transfers", receiveAddr), req) - if !broadcast { - return resp, body, receiveAddr - } - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, gasAdjustment, simulate, kb) - return resp, body, receiveAddr -} - -// signAndBroadcastGenTx accepts a successfully generated unsigned tx, signs it, -// and broadcasts it. -func signAndBroadcastGenTx( - t *testing.T, port, name, genTx string, acc authexported.Account, - gasAdjustment float64, simulate bool, kb crkeys.Keybase, -) (resp *http.Response, body string) { - - chainID := viper.GetString(flags.FlagChainID) - - var tx auth.StdTx - err := cdc.UnmarshalJSON([]byte(genTx), &tx) - require.Nil(t, err) - - txbldr := auth.NewTxBuilder( - authcutils.GetTxEncoder(cdc), - acc.GetAccountNumber(), - acc.GetSequence(), - tx.Fee.Gas, - gasAdjustment, - simulate, - chainID, - tx.Memo, - tx.Fee.Amount, - nil, - ).WithKeybase(kb) - - signedTx, err := txbldr.SignStdTx(name, clientkeys.DefaultKeyPass, tx, false) - require.NoError(t, err) - - return doBroadcast(t, port, signedTx) -} - -// ---------------------------------------------------------------------- -// ICS 21 - Stake -// ---------------------------------------------------------------------- - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doDelegate( - t *testing.T, port, name string, delAddr sdk.AccAddress, - valAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.DelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorAddress: valAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/delegations", delAddr.String()), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doUndelegate( - t *testing.T, port, name string, delAddr sdk.AccAddress, - valAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.UndelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorAddress: valAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// POST /staking/delegators/{delegatorAddr}/delegations Submit delegation -func doBeginRedelegation( - t *testing.T, port, name string, delAddr sdk.AccAddress, valSrcAddr, - valDstAddr sdk.ValAddress, amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, delAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - msg := stakingrest.RedelegateRequest{ - BaseReq: baseReq, - DelegatorAddress: delAddr, - ValidatorSrcAddress: valSrcAddr, - ValidatorDstAddress: valDstAddr, - Amount: sdk.NewCoin(sdk.DefaultBondDenom, amount), - } - - req, err := cdc.MarshalJSON(msg) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/staking/delegators/%s/redelegations", delAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /staking/delegators/{delegatorAddr}/delegations Get all delegations from a delegator -func getDelegatorDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) staking.DelegationResponses { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var dels staking.DelegationResponses - - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &dels) - require.Nil(t, err) - - return dels -} - -// GET /staking/delegators/{delegatorAddr}/unbonding_delegations Get all unbonding delegations from a delegator -func getDelegatorUnbondingDelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/unbonding_delegations", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var ubds []staking.UnbondingDelegation - - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &ubds) - require.Nil(t, err) - - return ubds -} - -// GET /staking/redelegations?delegator=0xdeadbeef&validator_from=0xdeadbeef&validator_to=0xdeadbeef& Get redelegations filters by params passed in -func getRedelegations(t *testing.T, port string, delegatorAddr sdk.AccAddress, srcValidatorAddr sdk.ValAddress, dstValidatorAddr sdk.ValAddress) staking.RedelegationResponses { - var res *http.Response - var body string - endpoint := "/staking/redelegations?" - if !delegatorAddr.Empty() { - endpoint += fmt.Sprintf("delegator=%s&", delegatorAddr) - } - if !srcValidatorAddr.Empty() { - endpoint += fmt.Sprintf("validator_from=%s&", srcValidatorAddr) - } - if !dstValidatorAddr.Empty() { - endpoint += fmt.Sprintf("validator_to=%s&", dstValidatorAddr) - } - - res, body = Request(t, port, "GET", endpoint, nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var redels staking.RedelegationResponses - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &redels) - require.Nil(t, err) - - return redels -} - -// GET /staking/delegators/{delegatorAddr}/validators Query all validators that a delegator is bonded to -func getDelegatorValidators(t *testing.T, port string, delegatorAddr sdk.AccAddress) []staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators", delegatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bondedValidators []staking.Validator - - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &bondedValidators) - require.Nil(t, err) - - return bondedValidators -} - -// GET /staking/delegators/{delegatorAddr}/validators/{validatorAddr} Query a validator that a delegator is bonded to -func getDelegatorValidator(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/validators/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bondedValidator staking.Validator - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &bondedValidator) - require.Nil(t, err) - - return bondedValidator -} - -// GET /staking/delegators/{delegatorAddr}/txs Get all staking txs (i.e msgs) from a delegator -func getBondingTxs(t *testing.T, port string, delegatorAddr sdk.AccAddress, query string) []sdk.TxResponse { - var res *http.Response - var body string - - if len(query) > 0 { - res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs?type=%s", delegatorAddr, query), nil) - } else { - res, body = Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/txs", delegatorAddr), nil) - } - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var txs []sdk.TxResponse - - err := cdc.UnmarshalJSON([]byte(body), &txs) - require.Nil(t, err) - - return txs -} - -// GET /staking/delegators/{delegatorAddr}/delegations/{validatorAddr} Query the current delegation between a delegator and a validator -func getDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, validatorAddr sdk.ValAddress) staking.DelegationResponse { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/delegators/%s/delegations/%s", delegatorAddr, validatorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var bond staking.DelegationResponse - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &bond) - require.Nil(t, err) - - return bond -} - -// GET /staking/delegators/{delegatorAddr}/unbonding_delegations/{validatorAddr} Query all unbonding delegations between a delegator and a validator -func getUnbondingDelegation(t *testing.T, port string, delegatorAddr sdk.AccAddress, - validatorAddr sdk.ValAddress) staking.UnbondingDelegation { - - res, body := Request(t, port, "GET", - fmt.Sprintf("/staking/delegators/%s/unbonding_delegations/%s", - delegatorAddr, validatorAddr), nil) - - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var unbond staking.UnbondingDelegation - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &unbond) - require.Nil(t, err) - - return unbond -} - -// GET /staking/validators Get all validator candidates -func getValidators(t *testing.T, port string) []staking.Validator { - res, body := Request(t, port, "GET", "/staking/validators", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var validators []staking.Validator - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &validators) - require.Nil(t, err) - - return validators -} - -// GET /staking/validators/{validatorAddr} Query the information from a single validator -func getValidator(t *testing.T, port string, validatorAddr sdk.ValAddress) staking.Validator { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var validator staking.Validator - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &validator) - require.Nil(t, err) - - return validator -} - -// GET /staking/validators/{validatorAddr}/delegations Get all delegations from a validator -func getValidatorDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.Delegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/delegations", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var delegations []staking.Delegation - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &delegations) - require.Nil(t, err) - - return delegations -} - -// GET /staking/validators/{validatorAddr}/unbonding_delegations Get all unbonding delegations from a validator -func getValidatorUnbondingDelegations(t *testing.T, port string, validatorAddr sdk.ValAddress) []staking.UnbondingDelegation { - res, body := Request(t, port, "GET", fmt.Sprintf("/staking/validators/%s/unbonding_delegations", validatorAddr.String()), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var ubds []staking.UnbondingDelegation - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &ubds) - require.Nil(t, err) - - return ubds -} - -// ---------------------------------------------------------------------- -// ICS 22 - Gov -// ---------------------------------------------------------------------- -// POST /gov/proposals Submit a proposal -func doSubmitProposal( - t *testing.T, port, name string, proposerAddr sdk.AccAddress, - amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - pr := govrest.PostProposalReq{ - Title: "Test", - Description: "test", - ProposalType: "Text", - Proposer: proposerAddr, - InitialDeposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(pr) - require.NoError(t, err) - - // submitproposal - resp, body := Request(t, port, "POST", "/gov/proposals", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -func doSubmitParamChangeProposal( - t *testing.T, port, name string, proposerAddr sdk.AccAddress, - amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - pr := paramscutils.ParamChangeProposalReq{ - BaseReq: baseReq, - Title: "Test", - Description: "test", - Proposer: proposerAddr, - Deposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - Changes: paramscutils.ParamChangesJSON{ - paramscutils.NewParamChangeJSON("staking", "MaxValidators", json.RawMessage(`105`)), - }, - } - - req, err := cdc.MarshalJSON(pr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", "/gov/proposals/param_change", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -func doSubmitCommunityPoolSpendProposal( - t *testing.T, port, name string, proposerAddr sdk.AccAddress, - amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - pr := distrrest.CommunityPoolSpendProposalReq{ - BaseReq: baseReq, - Title: "Test", - Description: "test", - Proposer: proposerAddr, - Recipient: proposerAddr, - Deposit: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - Amount: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(5))}, - } - - req, err := cdc.MarshalJSON(pr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", "/gov/proposals/community_pool_spend", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals Query proposals -func getProposalsAll(t *testing.T, port string) []gov.Proposal { - res, body := Request(t, port, "GET", "/gov/proposals", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?depositor=%s Query proposals -func getProposalsFilterDepositor(t *testing.T, port string, depositorAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s", depositorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?voter=%s Query proposals -func getProposalsFilterVoter(t *testing.T, port string, voterAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?voter=%s", voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?depositor=%s&voter=%s Query proposals -func getProposalsFilterVoterDepositor(t *testing.T, port string, voterAddr, depositorAddr sdk.AccAddress) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?depositor=%s&voter=%s", depositorAddr, voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposals) - require.Nil(t, err) - return proposals -} - -// GET /gov/proposals?status=%s Query proposals -func getProposalsFilterStatus(t *testing.T, port string, status gov.ProposalStatus) []gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals?status=%s", status), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposals []gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposals) - require.Nil(t, err) - return proposals -} - -// POST /gov/proposals/{proposalId}/deposits Deposit tokens to a proposal -func doDeposit( - t *testing.T, port, name string, proposerAddr sdk.AccAddress, - proposalID uint64, amount sdk.Int, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - dr := govrest.DepositReq{ - Depositor: proposerAddr, - Amount: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, amount)}, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(dr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/deposits", proposalID), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals/{proposalId}/deposits Query deposits -func getDeposits(t *testing.T, port string, proposalID uint64) []gov.Deposit { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var deposits []gov.Deposit - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &deposits) - require.Nil(t, err) - return deposits -} - -// GET /gov/proposals/{proposalId}/tally Get a proposal's tally result at the current time -func getTally(t *testing.T, port string, proposalID uint64) gov.TallyResult { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/tally", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var tally gov.TallyResult - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &tally) - require.Nil(t, err) - - return tally -} - -// POST /gov/proposals/{proposalId}/votes Vote a proposal -func doVote( - t *testing.T, port, name string, proposerAddr sdk.AccAddress, - proposalID uint64, option string, fees sdk.Coins, - kb crkeys.Keybase, -) sdk.TxResponse { - - // get the account to get the sequence - acc := getAccount(t, port, proposerAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - vr := govrest.VoteReq{ - Voter: proposerAddr, - Option: option, - BaseReq: baseReq, - } - - req, err := cdc.MarshalJSON(vr) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/gov/proposals/%d/votes", proposalID), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// GET /gov/proposals/{proposalId}/votes Query voters -func getVotes(t *testing.T, port string, proposalID uint64) []gov.Vote { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - var votes []gov.Vote - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &votes) - require.Nil(t, err) - return votes -} - -// GET /gov/proposals/{proposalId} Query a proposal -func getProposal(t *testing.T, port string, proposalID uint64) gov.Proposal { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposal gov.Proposal - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposal) - require.Nil(t, err) - - return proposal -} - -// GET /gov/proposals/{proposalId}/deposits/{depositor} Query deposit -func getDeposit(t *testing.T, port string, proposalID uint64, depositorAddr sdk.AccAddress) gov.Deposit { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/deposits/%s", proposalID, depositorAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var deposit gov.Deposit - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &deposit) - require.Nil(t, err) - - return deposit -} - -// GET /gov/proposals/{proposalId}/votes/{voter} Query vote -func getVote(t *testing.T, port string, proposalID uint64, voterAddr sdk.AccAddress) gov.Vote { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/votes/%s", proposalID, voterAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var vote gov.Vote - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &vote) - require.Nil(t, err) - - return vote -} - -// GET /gov/proposals/{proposalId}/proposer -func getProposer(t *testing.T, port string, proposalID uint64) gcutils.Proposer { - res, body := Request(t, port, "GET", fmt.Sprintf("/gov/proposals/%d/proposer", proposalID), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var proposer gcutils.Proposer - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &proposer) - - require.Nil(t, err) - return proposer -} - -// GET /gov/parameters/deposit Query governance deposit parameters -func getDepositParam(t *testing.T, port string) gov.DepositParams { - res, body := Request(t, port, "GET", "/gov/parameters/deposit", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var depositParams gov.DepositParams - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &depositParams) - require.Nil(t, err) - - return depositParams -} - -// GET /gov/parameters/tallying Query governance tally parameters -func getTallyingParam(t *testing.T, port string) gov.TallyParams { - res, body := Request(t, port, "GET", "/gov/parameters/tallying", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var tallyParams gov.TallyParams - err := cdc.UnmarshalJSON([]byte(body), &tallyParams) - require.Nil(t, err) - return tallyParams -} - -// GET /gov/parameters/voting Query governance voting parameters -func getVotingParam(t *testing.T, port string) gov.VotingParams { - res, body := Request(t, port, "GET", "/gov/parameters/voting", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var votingParams gov.VotingParams - err := cdc.UnmarshalJSON([]byte(body), &votingParams) - require.Nil(t, err) - return votingParams -} - -// ---------------------------------------------------------------------- -// ICS 23 - Slashing -// ---------------------------------------------------------------------- -// GET /slashing/validators/{validatorPubKey}/signing_info Get sign info of given validator -func getSigningInfo(t *testing.T, port string, validatorPubKey string) slashing.ValidatorSigningInfo { - res, body := Request(t, port, "GET", fmt.Sprintf("/slashing/validators/%s/signing_info", validatorPubKey), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var signingInfo slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &signingInfo) - require.Nil(t, err) - - return signingInfo -} - -// ---------------------------------------------------------------------- -// ICS 23 - SlashingList -// ---------------------------------------------------------------------- -// GET /slashing/signing_infos Get sign info of all validators with pagination -func getSigningInfoList(t *testing.T, port string) []slashing.ValidatorSigningInfo { - res, body := Request(t, port, "GET", "/slashing/signing_infos?page=1&limit=1", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var signingInfo []slashing.ValidatorSigningInfo - err := cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &signingInfo) - require.Nil(t, err) - - return signingInfo -} - -// TODO: Test this functionality, it is not currently in any of the tests -// POST /slashing/validators/{validatorAddr}/unjail Unjail a jailed validator -func doUnjail( - t *testing.T, port, name string, valAddr sdk.ValAddress, fees sdk.Coins, -) sdk.TxResponse { - - acc := getAccount(t, port, sdk.AccAddress(valAddr.Bytes())) - from := acc.GetAddress().String() - chainID := viper.GetString(flags.FlagChainID) - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", 1, 1, fees, nil, false) - ur := slashingrest.UnjailReq{ - BaseReq: baseReq, - } - req, err := cdc.MarshalJSON(ur) - require.NoError(t, err) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/slashing/validators/%s/unjail", valAddr.String()), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, nil) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err = cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} - -// ICS24 - fee distribution - -// POST /distribution/delegators/{delgatorAddr}/rewards Withdraw delegator rewards -func doWithdrawDelegatorAllRewards( - t *testing.T, port, name string, delegatorAddr sdk.AccAddress, fees sdk.Coins, -) sdk.TxResponse { - // get the account to get the sequence - acc := getAccount(t, port, delegatorAddr) - accnum := acc.GetAccountNumber() - sequence := acc.GetSequence() - chainID := viper.GetString(flags.FlagChainID) - from := acc.GetAddress().String() - - baseReq := rest.NewBaseReq(from, "", chainID, "", "", accnum, sequence, fees, nil, false) - wr := struct { - BaseReq rest.BaseReq `json:"base_req"` - }{BaseReq: baseReq} - - req := cdc.MustMarshalJSON(wr) - - resp, body := Request(t, port, "POST", fmt.Sprintf("/distribution/delegators/%s/rewards", delegatorAddr), req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - resp, body = signAndBroadcastGenTx(t, port, name, body, acc, flags.DefaultGasAdjustment, false, nil) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - var txResp sdk.TxResponse - err := cdc.UnmarshalJSON([]byte(body), &txResp) - require.NoError(t, err) - - return txResp -} diff --git a/lcd_test/lcd_test.go b/lcd_test/lcd_test.go deleted file mode 100644 index 7452672ae1..0000000000 --- a/lcd_test/lcd_test.go +++ /dev/null @@ -1,1128 +0,0 @@ -//nolint:bodyclose -package lcdtest - -import ( - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "net/http" - "os" - "strings" - "testing" - "time" - - "github.com/spf13/viper" - "github.com/stretchr/testify/require" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/crypto/keys" - "github.com/cosmos/cosmos-sdk/crypto/keys/mintkey" - "github.com/cosmos/cosmos-sdk/tests" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/version" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - distrrest "github.com/cosmos/cosmos-sdk/x/distribution/client/rest" - disttypes "github.com/cosmos/cosmos-sdk/x/distribution/types" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/mint" - "github.com/cosmos/cosmos-sdk/x/slashing" -) - -const ( - name1 = "test1" - memo = "LCD test tx" -) - -var fees = sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 5)} - -func init() { - mintkey.BcryptSecurityParameter = 1 - version.Version = os.Getenv("VERSION") -} - -func newKeybase() (keys.Keybase, error) { - return keys.NewKeyring( - sdk.KeyringServiceName(), - viper.GetString(flags.FlagKeyringBackend), - InitClientHome(""), - nil, - ) -} - -// nolint: errcheck -func TestMain(m *testing.M) { - viper.Set(flags.FlagKeyringBackend, "test") - os.Exit(m.Run()) -} - -func TestNodeStatus(t *testing.T) { - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - getNodeInfo(t, port) - getSyncStatus(t, port, false) -} - -func TestBlock(t *testing.T) { - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - getBlock(t, port, -1, false) - getBlock(t, port, 2, false) - getBlock(t, port, 100000000, true) -} - -func TestValidators(t *testing.T) { - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - resultVals := getValidatorSets(t, port, -1, false) - require.Contains(t, resultVals.Validators[0].Address.String(), "cosmosvalcons") - require.Contains(t, resultVals.Validators[0].PubKey, "cosmosvalconspub") - getValidatorSets(t, port, 2, false) - getValidatorSets(t, port, 10000000, true) -} - -func TestCoinSend(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6") - require.NoError(t, err) - someFakeAddr := sdk.AccAddress(bz) - - // query empty - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create TX - receiveAddr, resultTx := doTransfer(t, port, name1, memo, addr, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - // query sender - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - - require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) - require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) - expectedBalance = coins[0] - - // query receiver - acc2 := getAccount(t, port, receiveAddr) - coins2 := acc2.GetCoins() - require.Equal(t, sdk.DefaultBondDenom, coins2[0].Denom) - require.Equal(t, int64(1), coins2[0].Amount.Int64()) - - // test failure with too little gas - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, "100", 0, false, true, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Nil(t, err) - - // test failure with negative gas - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, "-200", 0, false, false, fees, kb) - require.Equal(t, http.StatusBadRequest, res.StatusCode, body) - - // test failure with negative adjustment - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, "10000", -0.1, true, false, fees, kb) - require.Equal(t, http.StatusBadRequest, res.StatusCode, body) - - // test failure with 0 gas - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, "0", 0, false, true, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - // test failure with wrong adjustment - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, flags.GasFlagAuto, 0.1, false, true, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - // run simulation and test success with estimated gas - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, "10000", 1.0, true, false, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var gasEstResp rest.GasEstimateResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &gasEstResp)) - require.NotZero(t, gasEstResp.GasEstimate) - - acc = getAccount(t, port, addr) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // run successful tx - gas := fmt.Sprintf("%d", gasEstResp.GasEstimate) - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, gas, 1.0, false, true, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - err = cdc.UnmarshalJSON([]byte(body), &resultTx) - require.Nil(t, err) - - tests.WaitForHeight(resultTx.Height+1, port) - require.Equal(t, uint32(0), resultTx.Code) - - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.SubRaw(1), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) -} - -func TestCoinSendAccAuto(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // send a transfer tx without specifying account number and sequence - res, body, _ := doTransferWithGasAccAuto( - t, port, name1, memo, addr, "200000", 1.0, false, true, fees, kb, - ) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - // query sender - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - - require.Equal(t, sdk.DefaultBondDenom, coins[0].Denom) - require.Equal(t, expectedBalance.Amount.SubRaw(1), coins[0].Amount) -} - -func TestCoinMultiSendGenerateOnly(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - // generate only - res, body, _ := doTransferWithGas(t, port, "", memo, addr, "200000", 1, false, false, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var stdTx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &stdTx)) - require.Equal(t, len(stdTx.Msgs), 1) - require.Equal(t, stdTx.GetMsgs()[0].Route(), bank.RouterKey) - require.Equal(t, stdTx.GetMsgs()[0].GetSigners(), []sdk.AccAddress{addr}) - require.Equal(t, 0, len(stdTx.Signatures)) - require.Equal(t, memo, stdTx.Memo) - require.NotZero(t, stdTx.Fee.Gas) - require.IsType(t, stdTx.GetMsgs()[0], bank.MsgSend{}) - require.Equal(t, addr, stdTx.GetMsgs()[0].(bank.MsgSend).FromAddress) -} - -func TestCoinSendGenerateSignAndBroadcast(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - acc := getAccount(t, port, addr) - - // simulate tx - res, body, _ := doTransferWithGas(t, port, name1, memo, addr, flags.GasFlagAuto, 1.0, true, false, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var gasEstResp rest.GasEstimateResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &gasEstResp)) - require.NotZero(t, gasEstResp.GasEstimate) - - // generate tx - gas := fmt.Sprintf("%d", gasEstResp.GasEstimate) - res, body, _ = doTransferWithGas(t, port, name1, memo, addr, gas, 1, false, false, fees, kb) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var tx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx)) - require.Equal(t, len(tx.Msgs), 1) - require.Equal(t, tx.Msgs[0].Route(), bank.RouterKey) - require.Equal(t, tx.Msgs[0].GetSigners(), []sdk.AccAddress{addr}) - require.Equal(t, 0, len(tx.Signatures)) - require.Equal(t, memo, tx.Memo) - require.NotZero(t, tx.Fee.Gas) - - gasEstimate := int64(tx.Fee.Gas) - _, body = signAndBroadcastGenTx(t, port, name1, body, acc, 1.0, false, kb) - - // check if tx was committed - var txResp sdk.TxResponse - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &txResp)) - require.Equal(t, uint32(0), txResp.Code) - require.Equal(t, gasEstimate, txResp.GasWanted) -} - -func TestEncodeTx(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - _, body, _ := doTransferWithGas(t, port, name1, memo, addr, "2", 1, false, false, fees, kb) - var tx auth.StdTx - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &tx)) - - encodedJSON, err := cdc.MarshalJSON(tx) - require.NoError(t, err) - res, body := Request(t, port, "POST", "/txs/encode", encodedJSON) - - // Make sure it came back ok, and that we can decode it back to the transaction - // 200 response. - require.Equal(t, http.StatusOK, res.StatusCode, body) - encodeResp := struct { - Tx string `json:"tx"` - }{} - - require.Nil(t, cdc.UnmarshalJSON([]byte(body), &encodeResp)) - - // verify that the base64 decodes - decodedBytes, err := base64.StdEncoding.DecodeString(encodeResp.Tx) - require.Nil(t, err) - - // check that the transaction decodes as expected - var decodedTx auth.StdTx - require.Nil(t, cdc.UnmarshalBinaryLengthPrefixed(decodedBytes, &decodedTx)) - require.Equal(t, memo, decodedTx.Memo) -} - -func TestTxs(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - var emptyTxs []sdk.TxResponse - txResult := getTransactions(t, port) - require.Equal(t, emptyTxs, txResult.Txs) - - // query empty - txResult = getTransactions(t, port, fmt.Sprintf("message.sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - // also tests url decoding - txResult = getTransactions(t, port, fmt.Sprintf("message.sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - txResult = getTransactions(t, port, fmt.Sprintf("message.action=submit_proposal&message.sender=%s", addr.String())) - require.Equal(t, emptyTxs, txResult.Txs) - - // create tx - receiveAddr, resultTx := doTransfer(t, port, name1, memo, addr, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx is queryable - tx := getTransaction(t, port, resultTx.TxHash) - require.Equal(t, resultTx.TxHash, tx.TxHash) - - // query sender - txResult = getTransactions(t, port, fmt.Sprintf("message.sender=%s", addr.String())) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query recipient - txResult = getTransactions(t, port, fmt.Sprintf("transfer.recipient=%s", receiveAddr.String())) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query transaction that doesn't exist - validTxHash := "9ADBECAAD8DACBEC3F4F535704E7CF715C765BDCEDBEF086AFEAD31BA664FB0B" - res, body := getTransactionRequest(t, port, validTxHash) - require.True(t, strings.Contains(body, validTxHash)) - require.Equal(t, http.StatusNotFound, res.StatusCode) - - // bad query string - res, body = getTransactionRequest(t, port, "badtxhash") - require.True(t, strings.Contains(body, "encoding/hex")) - require.Equal(t, http.StatusInternalServerError, res.StatusCode) -} - -func TestValidatorsQuery(t *testing.T) { - cleanup, valPubKeys, operAddrs, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - - require.Equal(t, 1, len(valPubKeys)) - require.Equal(t, 1, len(operAddrs)) - - validators := getValidators(t, port) - require.Equal(t, 1, len(validators), fmt.Sprintf("%+v", validators)) - - // make sure all the validators were found (order unknown because sorted by operator addr) - foundVal := false - - if validators[0].ConsPubKey == valPubKeys[0] { - foundVal = true - } - - require.True(t, foundVal, "pk %v, operator %v", operAddrs[0], validators[0].OperatorAddress) -} - -func TestValidatorQuery(t *testing.T) { - cleanup, valPubKeys, operAddrs, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - require.Equal(t, 1, len(valPubKeys)) - require.Equal(t, 1, len(operAddrs)) - - validator := getValidator(t, port, operAddrs[0]) - require.Equal(t, validator.OperatorAddress, operAddrs[0], "The returned validator does not hold the correct data") -} - -func TestBonding(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - - cleanup, valPubKeys, operAddrs, port, err := InitializeLCD(2, []sdk.AccAddress{addr}, false) - require.NoError(t, err) - tests.WaitForHeight(1, port) - defer cleanup() - - require.Equal(t, 2, len(valPubKeys)) - require.Equal(t, 2, len(operAddrs)) - - amt := sdk.TokensFromConsensusPower(60) - amtDec := amt.ToDec() - validator := getValidator(t, port, operAddrs[0]) - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create bond TX - delTokens := sdk.TokensFromConsensusPower(60) - resultTx := doDelegate(t, port, name1, addr, operAddrs[0], delTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - require.Equal(t, uint32(0), resultTx.Code) - - // query tx - txResult := getTransactions(t, port, - fmt.Sprintf("message.action=delegate&message.sender=%s", addr), - fmt.Sprintf("delegate.validator=%s", operAddrs[0]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens).String(), coins.AmountOf(sdk.DefaultBondDenom).String()) - expectedBalance = coins[0] - - // query delegation - bond := getDelegation(t, port, addr, operAddrs[0]) - require.Equal(t, amtDec, bond.Shares) - - delegatorDels := getDelegatorDelegations(t, port, addr) - require.Len(t, delegatorDels, 1) - require.Equal(t, amtDec, delegatorDels[0].Shares) - - // query all delegations to validator - bonds := getValidatorDelegations(t, port, operAddrs[0]) - require.Len(t, bonds, 2) - - bondedValidators := getDelegatorValidators(t, port, addr) - require.Len(t, bondedValidators, 1) - require.Equal(t, operAddrs[0], bondedValidators[0].OperatorAddress) - require.Equal(t, validator.DelegatorShares.Add(amtDec).String(), bondedValidators[0].DelegatorShares.String()) - - bondedValidator := getDelegatorValidator(t, port, addr, operAddrs[0]) - require.Equal(t, operAddrs[0], bondedValidator.OperatorAddress) - - // testing unbonding - unbondingTokens := sdk.TokensFromConsensusPower(30) - resultTx = doUndelegate(t, port, name1, addr, operAddrs[0], unbondingTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - require.Equal(t, uint32(0), resultTx.Code) - - // sender should have not received any coins as the unbonding has only just begun - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), - "should get tokens back from automatic withdrawal after an unbonding delegation", - ) - expectedBalance = coins[0] - - // query tx - txResult = getTransactions(t, port, - fmt.Sprintf("message.action=begin_unbonding&message.sender=%s", addr), - fmt.Sprintf("unbond.validator=%s", operAddrs[0]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - ubd := getUnbondingDelegation(t, port, addr, operAddrs[0]) - require.Len(t, ubd.Entries, 1) - require.Equal(t, delTokens.QuoRaw(2), ubd.Entries[0].Balance) - - // test redelegation - rdTokens := sdk.TokensFromConsensusPower(30) - resultTx = doBeginRedelegation(t, port, name1, addr, operAddrs[0], operAddrs[1], rdTokens, fees, kb) - require.Equal(t, uint32(0), resultTx.Code) - tests.WaitForHeight(resultTx.Height+1, port) - - // query delegations, unbondings and redelegations from validator and delegator - delegatorDels = getDelegatorDelegations(t, port, addr) - require.Len(t, delegatorDels, 1) - require.Equal(t, operAddrs[1], delegatorDels[0].ValidatorAddress) - - // TODO uncomment once all validators actually sign in the lcd tests - //validator2 := getValidator(t, port, operAddrs[1]) - //delTokensAfterRedelegation := validator2.ShareTokens(delegatorDels[0].GetShares()) - //require.Equal(t, rdTokens.ToDec(), delTokensAfterRedelegation) - - // verify balance after paying fees - expectedBalance = expectedBalance.Sub(fees[0]) - require.True(t, - expectedBalance.Amount.LT(coins.AmountOf(sdk.DefaultBondDenom)) || - expectedBalance.Amount.Equal(coins.AmountOf(sdk.DefaultBondDenom)), - "should get tokens back from automatic withdrawal after an unbonding delegation", - ) - - // query tx - txResult = getTransactions(t, port, - fmt.Sprintf("message.action=begin_redelegate&message.sender=%s", addr), - fmt.Sprintf("redelegate.source_validator=%s", operAddrs[0]), - fmt.Sprintf("redelegate.destination_validator=%s", operAddrs[1]), - ) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - redelegation := getRedelegations(t, port, addr, operAddrs[0], operAddrs[1]) - require.Len(t, redelegation, 1) - require.Len(t, redelegation[0].Entries, 1) - - delegatorUbds := getDelegatorUnbondingDelegations(t, port, addr) - require.Len(t, delegatorUbds, 1) - require.Len(t, delegatorUbds[0].Entries, 1) - require.Equal(t, rdTokens, delegatorUbds[0].Entries[0].Balance) - - delegatorReds := getRedelegations(t, port, addr, nil, nil) - require.Len(t, delegatorReds, 1) - require.Len(t, delegatorReds[0].Entries, 1) - - validatorUbds := getValidatorUnbondingDelegations(t, port, operAddrs[0]) - require.Len(t, validatorUbds, 1) - require.Len(t, validatorUbds[0].Entries, 1) - require.Equal(t, rdTokens, validatorUbds[0].Entries[0].Balance) - - validatorReds := getRedelegations(t, port, nil, operAddrs[0], nil) - require.Len(t, validatorReds, 1) - require.Len(t, validatorReds[0].Entries, 1) - - // TODO Undonding status not currently implemented - // require.Equal(t, sdk.Unbonding, bondedValidators[0].Status) - - // query txs - txs := getBondingTxs(t, port, addr, "") - require.Len(t, txs, 3, "All Txs found") - - txs = getBondingTxs(t, port, addr, "bond") - require.Len(t, txs, 1, "All bonding txs found") - - txs = getBondingTxs(t, port, addr, "unbond") - require.Len(t, txs, 1, "All unbonding txs found") - - txs = getBondingTxs(t, port, addr, "redelegate") - require.Len(t, txs, 1, "All redelegation txs found") -} - -func TestSubmitProposal(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromConsensusPower(5) - resultTx := doSubmitProposal(t, port, name1, addr, proposalTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - proposalID := gov.GetProposalIDFromBytes(bz) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - proposer := getProposer(t, port, proposalID) - require.Equal(t, addr.String(), proposer.Proposer) - require.Equal(t, proposalID, proposer.ProposalID) -} - -func TestSubmitCommunityPoolSpendProposal(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create proposal tx - proposalTokens := sdk.TokensFromConsensusPower(5) - resultTx := doSubmitCommunityPoolSpendProposal(t, port, name1, addr, proposalTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - proposalID := gov.GetProposalIDFromBytes(bz) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - proposer := getProposer(t, port, proposalID) - require.Equal(t, addr.String(), proposer.Proposer) - require.Equal(t, proposalID, proposer.ProposalID) -} - -func TestSubmitParamChangeProposal(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create proposal tx - proposalTokens := sdk.TokensFromConsensusPower(5) - resultTx := doSubmitParamChangeProposal(t, port, name1, addr, proposalTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - proposalID := gov.GetProposalIDFromBytes(bz) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - proposer := getProposer(t, port, proposalID) - require.Equal(t, addr.String(), proposer.Proposer) - require.Equal(t, proposalID, proposer.ProposalID) -} - -func TestDeposit(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromConsensusPower(5) - resultTx := doSubmitProposal(t, port, name1, addr, proposalTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - proposalID := gov.GetProposalIDFromBytes(bz) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - - // create SubmitProposal TX - depositTokens := sdk.TokensFromConsensusPower(5) - resultTx = doDeposit(t, port, name1, addr, proposalID, depositTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance after deposit and fee - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(depositTokens), acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - // query tx - txResult := getTransactions(t, port, fmt.Sprintf("message.action=deposit&message.sender=%s", addr)) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - // query proposal - totalCoins := sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, sdk.TokensFromConsensusPower(10))} - proposal = getProposal(t, port, proposalID) - require.True(t, proposal.TotalDeposit.IsEqual(totalCoins)) - - // query deposit - deposit := getDeposit(t, port, proposalID, addr) - require.True(t, deposit.Amount.IsEqual(totalCoins)) -} - -func TestVote(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, operAddrs, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - acc := getAccount(t, port, addr) - initialBalance := acc.GetCoins() - - // create SubmitProposal TX - proposalTokens := sdk.TokensFromConsensusPower(10) - resultTx := doSubmitProposal(t, port, name1, addr, proposalTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check if tx was committed - require.Equal(t, uint32(0), resultTx.Code) - - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - proposalID := gov.GetProposalIDFromBytes(bz) - - // verify balance - acc = getAccount(t, port, addr) - coins := acc.GetCoins() - expectedBalance := initialBalance[0].Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(proposalTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query proposal - proposal := getProposal(t, port, proposalID) - require.Equal(t, "Test", proposal.GetTitle()) - require.Equal(t, gov.StatusVotingPeriod, proposal.Status) - - // vote - resultTx = doVote(t, port, name1, addr, proposalID, "Yes", fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance after vote and fee - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount, coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - // query tx - txResult := getTransactions(t, port, fmt.Sprintf("message.action=vote&message.sender=%s", addr)) - require.Len(t, txResult.Txs, 1) - require.Equal(t, resultTx.Height, txResult.Txs[0].Height) - - vote := getVote(t, port, proposalID, addr) - require.Equal(t, proposalID, vote.ProposalID) - require.Equal(t, gov.OptionYes, vote.Option) - - tally := getTally(t, port, proposalID) - require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 as the address is not bonded") - - // create bond TX - delTokens := sdk.TokensFromConsensusPower(60) - resultTx = doDelegate(t, port, name1, addr, operAddrs[0], delTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance - acc = getAccount(t, port, addr) - coins = acc.GetCoins() - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount.Sub(delTokens), coins.AmountOf(sdk.DefaultBondDenom)) - expectedBalance = coins[0] - - tally = getTally(t, port, proposalID) - require.Equal(t, delTokens, tally.Yes, "tally should be equal to the amount delegated") - - // change vote option - resultTx = doVote(t, port, name1, addr, proposalID, "No", fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // verify balance - acc = getAccount(t, port, addr) - expectedBalance = expectedBalance.Sub(fees[0]) - require.Equal(t, expectedBalance.Amount, acc.GetCoins().AmountOf(sdk.DefaultBondDenom)) - - tally = getTally(t, port, proposalID) - require.Equal(t, sdk.ZeroInt(), tally.Yes, "tally should be 0 the user changed the option") - require.Equal(t, delTokens, tally.No, "tally should be equal to the amount delegated") -} - -func TestUnjail(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, valPubKeys, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - // NOTE: any less than this and it fails - tests.WaitForHeight(3, port) - pkString, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, valPubKeys[0]) - require.NoError(t, err) - signingInfo := getSigningInfo(t, port, pkString) - tests.WaitForHeight(4, port) - require.Equal(t, true, signingInfo.IndexOffset > 0) - require.Equal(t, time.Unix(0, 0).UTC(), signingInfo.JailedUntil) - require.Equal(t, true, signingInfo.MissedBlocksCounter == 0) - signingInfoList := getSigningInfoList(t, port) - require.NotZero(t, len(signingInfoList)) -} - -func TestProposalsQuery(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addrs, _, names, errors := CreateAddrs(kb, 2) - require.Empty(t, errors) - - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addrs[0], addrs[1]}, true) - require.NoError(t, err) - defer cleanup() - - depositParam := getDepositParam(t, port) - halfMinDeposit := depositParam.MinDeposit.AmountOf(sdk.DefaultBondDenom).QuoRaw(2) - getVotingParam(t, port) - getTallyingParam(t, port) - - // Addr1 proposes (and deposits) proposals #1 and #2 - resultTx := doSubmitProposal(t, port, names[0], addrs[0], halfMinDeposit, fees, kb) - bz, err := hex.DecodeString(resultTx.Data) - require.NoError(t, err) - - proposalID1 := gov.GetProposalIDFromBytes(bz) - tests.WaitForHeight(resultTx.Height+1, port) - - resultTx = doSubmitProposal(t, port, names[0], addrs[0], halfMinDeposit, fees, kb) - bz, err = hex.DecodeString(resultTx.Data) - require.NoError(t, err) - - proposalID2 := gov.GetProposalIDFromBytes(bz) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 proposes (and deposits) proposals #3 - resultTx = doSubmitProposal(t, port, names[1], addrs[1], halfMinDeposit, fees, kb) - bz, err = hex.DecodeString(resultTx.Data) - require.NoError(t, err) - - proposalID3 := gov.GetProposalIDFromBytes(bz) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 deposits on proposals #2 & #3 - resultTx = doDeposit(t, port, names[1], addrs[1], proposalID2, halfMinDeposit, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - resultTx = doDeposit(t, port, names[1], addrs[1], proposalID3, halfMinDeposit, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // check deposits match proposal and individual deposits - deposits := getDeposits(t, port, proposalID1) - require.Len(t, deposits, 1) - deposit := getDeposit(t, port, proposalID1, addrs[0]) - require.Equal(t, deposit, deposits[0]) - - deposits = getDeposits(t, port, proposalID2) - require.Len(t, deposits, 2) - deposit = getDeposit(t, port, proposalID2, addrs[0]) - require.True(t, deposit.Equals(deposits[0])) - deposit = getDeposit(t, port, proposalID2, addrs[1]) - require.True(t, deposit.Equals(deposits[1])) - - deposits = getDeposits(t, port, proposalID3) - require.Len(t, deposits, 1) - deposit = getDeposit(t, port, proposalID3, addrs[1]) - require.Equal(t, deposit, deposits[0]) - - // increasing the amount of the deposit should update the existing one - depositTokens := sdk.TokensFromConsensusPower(1) - resultTx = doDeposit(t, port, names[0], addrs[0], proposalID1, depositTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - deposits = getDeposits(t, port, proposalID1) - require.Len(t, deposits, 1) - - // Only proposals #1 should be in Deposit Period - proposals := getProposalsFilterStatus(t, port, gov.StatusDepositPeriod) - require.Len(t, proposals, 1) - require.Equal(t, proposalID1, proposals[0].ProposalID) - - // Only proposals #2 and #3 should be in Voting Period - proposals = getProposalsFilterStatus(t, port, gov.StatusVotingPeriod) - require.Len(t, proposals, 2) - require.Equal(t, proposalID2, proposals[0].ProposalID) - require.Equal(t, proposalID3, proposals[1].ProposalID) - - // Addr1 votes on proposals #2 & #3 - resultTx = doVote(t, port, names[0], addrs[0], proposalID2, "Yes", fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - resultTx = doVote(t, port, names[0], addrs[0], proposalID3, "Yes", fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // Addr2 votes on proposal #3 - resultTx = doVote(t, port, names[1], addrs[1], proposalID3, "Yes", fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - - // Test query all proposals - proposals = getProposalsAll(t, port) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) - require.Equal(t, proposalID2, (proposals[1]).ProposalID) - require.Equal(t, proposalID3, (proposals[2]).ProposalID) - - // Test query deposited by addr1 - proposals = getProposalsFilterDepositor(t, port, addrs[0]) - require.Equal(t, proposalID1, (proposals[0]).ProposalID) - - // Test query deposited by addr2 - proposals = getProposalsFilterDepositor(t, port, addrs[1]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) - - // Test query voted by addr1 - proposals = getProposalsFilterVoter(t, port, addrs[0]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - require.Equal(t, proposalID3, (proposals[1]).ProposalID) - - // Test query voted by addr2 - proposals = getProposalsFilterVoter(t, port, addrs[1]) - require.Equal(t, proposalID3, (proposals[0]).ProposalID) - - // Test query voted and deposited by addr1 - proposals = getProposalsFilterVoterDepositor(t, port, addrs[0], addrs[0]) - require.Equal(t, proposalID2, (proposals[0]).ProposalID) - - // Test query votes on Proposal 2 - votes := getVotes(t, port, proposalID2) - require.Len(t, votes, 1) - require.Equal(t, addrs[0], votes[0].Voter) - - // Test query votes on Proposal 3 - votes = getVotes(t, port, proposalID3) - require.Len(t, votes, 2) - require.True(t, addrs[0].String() == votes[0].Voter.String() || addrs[0].String() == votes[1].Voter.String()) - require.True(t, addrs[1].String() == votes[0].Voter.String() || addrs[1].String() == votes[1].Voter.String()) -} - -func TestSlashingGetParams(t *testing.T) { - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - - res, body := Request(t, port, "GET", "/slashing/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var params slashing.Params - err = cdc.UnmarshalJSON([]byte(body), ¶ms) - require.NoError(t, err) -} - -func TestDistributionGetParams(t *testing.T) { - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{}, true) - require.NoError(t, err) - defer cleanup() - - res, body := Request(t, port, "GET", "/distribution/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON([]byte(body), &disttypes.Params{})) -} - -func TestDistributionFlow(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, valAddrs, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - valAddr := valAddrs[0] - operAddr := sdk.AccAddress(valAddr) - - var rewards sdk.DecCoins - res, body := Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/outstanding_rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &rewards)) - - var valDistInfo distrrest.ValidatorDistInfo - res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &valDistInfo)) - require.Equal(t, valDistInfo.OperatorAddress.String(), sdk.AccAddress(valAddr).String()) - - // Delegate some coins - delTokens := sdk.TokensFromConsensusPower(60) - resultTx := doDelegate(t, port, name1, addr, valAddr, delTokens, fees, kb) - tests.WaitForHeight(resultTx.Height+1, port) - require.Equal(t, uint32(0), resultTx.Code) - - // send some coins - _, resultTx = doTransfer(t, port, name1, memo, addr, fees, kb) - tests.WaitForHeight(resultTx.Height+5, port) - require.Equal(t, uint32(0), resultTx.Code) - - // Query outstanding rewards changed - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/outstanding_rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &rewards)) - - // Query validator distribution info - res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &valDistInfo)) - - // Query validator's rewards - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/rewards", valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &rewards)) - - // Query self-delegation - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", operAddr, valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &rewards)) - - // Query delegation - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", addr, valAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &rewards)) - - // Query delegator's rewards total - var delRewards disttypes.QueryDelegatorTotalRewardsResponse - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards", operAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, json.Unmarshal(extractResultFromResponse(t, []byte(body)), &delRewards)) - - // Query delegator's withdrawal address - var withdrawAddr string - res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/withdraw_address", operAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &withdrawAddr)) - require.Equal(t, operAddr.String(), withdrawAddr) - - // Withdraw delegator's rewards - resultTx = doWithdrawDelegatorAllRewards(t, port, name1, addr, fees) - require.Equal(t, uint32(0), resultTx.Code) -} - -func TestMintingQueries(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - res, body := Request(t, port, "GET", "/minting/parameters", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var params mint.Params - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), ¶ms)) - - res, body = Request(t, port, "GET", "/minting/inflation", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var inflation sdk.Dec - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &inflation)) - - res, body = Request(t, port, "GET", "/minting/annual-provisions", nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - - var annualProvisions sdk.Dec - require.NoError(t, cdc.UnmarshalJSON(extractResultFromResponse(t, []byte(body)), &annualProvisions)) -} - -func TestAccountBalanceQuery(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []sdk.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - bz, err := hex.DecodeString("8FA6AB57AD6870F6B5B2E57735F38F2F30E73CB6") - require.NoError(t, err) - someFakeAddr := sdk.AccAddress(bz) - - // empty account - res, body := Request(t, port, "GET", fmt.Sprintf("/auth/accounts/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Contains(t, body, `"type":"cosmos-sdk/Account"`) - - // empty account balance - res, body = Request(t, port, "GET", fmt.Sprintf("/bank/balances/%s", someFakeAddr), nil) - require.Equal(t, http.StatusOK, res.StatusCode, body) - require.Contains(t, body, "[]") - -} diff --git a/lcd_test/testdata/setup.sh b/lcd_test/testdata/setup.sh deleted file mode 100755 index ffef42ad42..0000000000 --- a/lcd_test/testdata/setup.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env bash - -PASSWORD="1234567890" -ADDR="cosmos16xyempempp92x9hyzz9wrgf94r6j9h5f06pxxv" -RECEIVER="cosmos17gx5vwpm0y2k59tw0x00ccug234n56cgltx2w2" -VALIDATOR="cosmosvaloper16xyempempp92x9hyzz9wrgf94r6j9h5f2w4n2l" -AMOUNT="1000000stake" -CHAIN="lcd" -PROPOSALID="2" -HOME="/tmp/contract_tests/.wasmcli" -SWAGGER='/tmp/contract_tests/swagger.yaml' - -# sleeping a whole second between each step is a conservative precaution -# check lcd_test/testdata/state.tar.gz -> .wasmd/config/config.toml precommit_timeout = 500ms -sleep 1s -echo ${PASSWORD} | ./build/wasmcli tx gov submit-proposal --home ${HOME} --from ${ADDR} --chain-id ${CHAIN} --type text --title test --description test_description --deposit 10000stake --yes -sleep 1s -echo ${PASSWORD} | ./build/wasmcli tx gov deposit --home ${HOME} --from ${ADDR} --chain-id ${CHAIN} ${PROPOSALID} 1000000000stake --yes -sleep 1s -echo ${PASSWORD} | ./build/wasmcli tx gov vote --home ${HOME} --from ${ADDR} --yes --chain-id ${CHAIN} ${PROPOSALID} Yes -sleep 1s -HASH=$(echo ${PASSWORD} | ./build/wasmcli tx send --home ${HOME} ${ADDR} ${RECEIVER} ${AMOUNT} --yes --chain-id ${CHAIN} | awk '/txhash.*/{print $2}') -sed -i.bak -e "s/BCBE20E8D46758B96AE5883B792858296AC06E51435490FBDCAE25A72B3CC76B/${HASH}/g" "${SWAGGER}" -echo "Replaced dummy with actual transaction hash ${HASH}" -sleep 1s -echo ${PASSWORD} | ./build/wasmcli tx staking unbond --home ${HOME} --from ${ADDR} ${VALIDATOR} 100stake --yes --chain-id ${CHAIN} - diff --git a/lcd_test/testdata/state.tar.gz b/lcd_test/testdata/state.tar.gz deleted file mode 100644 index 30f0942309..0000000000 Binary files a/lcd_test/testdata/state.tar.gz and /dev/null differ diff --git a/lcd_test/wasm_test.go b/lcd_test/wasm_test.go deleted file mode 100644 index 7442373955..0000000000 --- a/lcd_test/wasm_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package lcdtest - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "testing" - - "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/spf13/viper" - "github.com/stretchr/testify/require" -) - -const firstCodeID = 1 - -func TestWasmStoreCode(t *testing.T) { - kb, err := newKeybase() - require.NoError(t, err) - addr, _, err := CreateAddr(name1, kb) - require.NoError(t, err) - cleanup, _, _, port, err := InitializeLCD(1, []types.AccAddress{addr}, true) - require.NoError(t, err) - defer cleanup() - - wasmCode, err := ioutil.ReadFile("../x/wasm/internal/keeper/testdata/hackatom.wasm") - require.NoError(t, err) - - var ( - chainID = viper.GetString(flags.FlagChainID) - from = addr.String() - acc = getAccount(t, port, addr) - accnum = acc.GetAccountNumber() - sequence = acc.GetSequence() - gas = "1200000" - simulate = false - gasAdjustment = 1.0 - ) - - baseReq := rest.NewBaseReq( - from, memo, chainID, gas, fmt.Sprintf("%f", gasAdjustment), accnum, sequence, fees, nil, simulate, - ) - storeCodeReq := struct { - BaseReq rest.BaseReq `json:"base_req" yaml:"base_req"` - WasmBytes []byte `json:"wasm_bytes"` - }{ - BaseReq: baseReq, - WasmBytes: wasmCode, - } - - req, err := cdc.MarshalJSON(storeCodeReq) - require.NoError(t, err) - - // generate tx - resp, body := Request(t, port, "POST", "/wasm/code", req) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - - // sign and broadcast - resp, body = signAndBroadcastGenTx(t, port, name1, body, acc, gasAdjustment, simulate, kb) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - var payload map[string]json.RawMessage - require.NoError(t, json.Unmarshal([]byte(body), &payload)) - require.Nil(t, payload["code"], body) - - // then check list view - resp, body = Request(t, port, "GET", "/wasm/code", nil) - require.Equal(t, http.StatusOK, resp.StatusCode, body) - var listPayload struct { - Height string - Result []map[string]interface{} - } - require.NoError(t, json.Unmarshal([]byte(body), &listPayload), body) - require.Len(t, listPayload.Result, 1) - - // and check detail view - resp, body = Request(t, port, "GET", fmt.Sprintf("/wasm/code/%d", firstCodeID), nil) - require.Equal(t, http.StatusOK, resp.StatusCode, body) -} diff --git a/scripts/protocgen.sh b/scripts/protocgen.sh new file mode 100755 index 0000000000..492b31abfd --- /dev/null +++ b/scripts/protocgen.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash + +set -eo pipefail + +project_dir=x/wasm/internal/types/ +cosmos_sdk_dir=$(go list -f "{{ .Dir }}" -m github.com/cosmos/cosmos-sdk) +# Generate Go types from protobuf +protoc \ + -I=. \ + -I="$cosmos_sdk_dir/third_party/proto" \ + -I="$cosmos_sdk_dir/proto" \ + --gocosmos_out=Mgoogle/protobuf/any.proto=github.com/cosmos/cosmos-sdk/codec/types,plugins=interfacetype+grpc,paths=source_relative:. \ + $(find "${project_dir}" -maxdepth 1 -name '*.proto') + +# Generate gRPC gateway (*.pb.gw.go in respective modules) files +protoc \ + -I=. \ + -I="$cosmos_sdk_dir/third_party/proto" \ + -I="$cosmos_sdk_dir/proto" \ + --grpc-gateway_out .\ + --grpc-gateway_opt logtostderr=true \ + --grpc-gateway_opt paths=source_relative \ + $(find "${project_dir}" -maxdepth 1 -name '*.proto') diff --git a/x/wasm/IBC.md b/x/wasm/IBC.md new file mode 100644 index 0000000000..a7a99948f6 --- /dev/null +++ b/x/wasm/IBC.md @@ -0,0 +1,440 @@ +# IBC specification + +This documents how CosmWasm contracts are expected to interact with IBC. + +## General Concepts + +**IBC Enabled** - when instantiating a contract, we detect if it supports IBC messages. + We require "feature flags" in the contract/vm handshake to ensure compatibility + for features like staking or chain-specific extensions. IBC functionality will require + another "feature flag", and the list of "enabled features" can be returned to the `x/wasm` + module to control conditional IBC behavior. + + If this feature is enabled, it is considered "IBC Enabled", and that info will + be stored in the ContractInfo. (For mock, we assume all contracts are IBC enabled) + +Also, please read the [IBC Docs](https://docs.cosmos.network/master/ibc/overview.html) +for detailed descriptions of the terms *Port*, *Client*, *Connection*, +and *Channel* + +## Overview + +We use "One Port per Contract", which is the most straight-forward mapping, treating each contract +like a module. It does lead to very long portIDs however. Pay special attention to both the Channel establishment +(which should be compatible with standard ICS20 modules without changes on their part), as well +as how contracts can properly identify their counterparty. + +(We considered on port for the `x/wasm` module and multiplexing on it, but [dismissed that idea](#rejected-ideas)) + +* Upon `Instantiate`, if a contract is *IBC Enabled*, we dynamically + bind a port for this contract. The port name is `wasm-`, + eg. `wasm-cosmos1hmdudppzceg27qsuq707tjg8rkgj7g5hnvnw29` +* If a *Channel* is being established with a registered `wasm-xyz` port, + the `x/wasm.Keeper` will handle this and call into the appropriate + contract to determine supported protocol versions during the + [`ChanOpenTry` and `ChanOpenAck` phases](https://docs.cosmos.network/master/ibc/overview.html#channels). + (See [Channel Handshake Version Negotiation](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation)) +* Both the *Port* and the *Channel* are fully owned by one contract. +* `x/wasm` will allow both *ORDERED* and *UNORDERED* channels and pass that mode + down to the contract in `OnChanOpenTry`, so the contract can decide if it accepts + the mode. We will recommend the contract developers stick with *ORDERED* channels + for custom protocols unless they can reason about async packet timing. +* When sending a packet, the CosmWasm contract must specify the local *ChannelID*. + As there is a unique *PortID* per contract, that is filled in by `x/wasm` + to produce the globally unique `(PortID, ChannelID)` +* When receiving a Packet (or Ack or Timeout), the contracts receives the + *ChannelID* it came from, as well as the packet that was sent by the counterparty. +* When receiving an Ack or Timeout packet, the contract also receives the + original packet that it sent earlier. +* We do not support multihop packets in this model (they are rejected by `x/wasm`). + They are currently not fully specified nor implemented in IBC 1.0, so let us + simplify our model until this is well established + +## Workflow + +Establishing *Clients* and *Connections* is out of the scope of this +module and must be created by the same means as for `ibc-transfer` +(via the cli or otherwise). `x/wasm` will bind a unique *Port* for each +"IBC Enabled" contract. + +For mocks, all the Packet Handling and Channel Lifecycle Hooks are routed +to some Golang stub handler, but containing the contract address, so we +can perform contract-specific actions for each packet. + +### Messages + +An "IBC Enabled" contract may dispatch the following messages not available +to other contracts: + +* `IBCSendMsg` - this sends an IBC packet over an established channel. +* `IBCCloseChannel` - given an existing channelID bound to this contract's Port, + initiate the closing sequence and reject all pending packets. + +They are returned from `handle` just like any other `CosmosMsg` +(For mocks, we will trigger this externally, later only valid contract addresses +should be able to do so). + +### Packet Handling + +An "IBC Enabled" contract must support the following callbacks from the runtime +(we will likely multiplex many over one wasm export, as we do with handle, but these +are the different calls we must support): + +* `IBCRecvPacket` - when another chain sends a packet destined to + an IBCEnabled contract, this will be routed to the proper contract + and call a function exposed for this purpose. +* `IBCPacketAck` - The original sender of `IBCSendMsg` will + get this callback eventually if the message was + processed on the other chain (this may be either a success or an error, + but comes from the app-level protocol, not the IBC protocol). +* `IBCPacketTimeout` - The original sender of `IBCSendMsg` will + get this callback eventually if the message failed to be + processed on the other chain (for timeout, closed channel, or + other IBC-level failure) + +Note: We may add some helpers inside the contract to map `IBCPacketAck` / `IBCPacketTimeout` +to `IBCPacketSucceeded` / `IBCPacketFailed` assuming they use the standard envelope. However, +we decided not to enforce this on the Go-level, to allow contracts to communicate using protocols +that do not use this envelope. + +### Channel Lifecycle Hooks + +If you look at the [4 step process](https://docs.cosmos.network/master/ibc/overview.html#channels) for +channel handshakes, we simplify this from the view of the contract: + +1. The main path to initiate a channel from a contract to an external port is via an external + client executing `simd tx ibc channel open-init` or such. This allows the initiating party + to select which version/protocol they want to connect with. There must be a callback for + the initiating contract to verify if the version and/or ordering are valid. + **Question**: can we reuse the same check-logic as for step 2 +2. The counterparty has a chance for version negotiation in `OnChanOpenTry`, where the contract + can apply custom logic. It provides the protocol versions that the initiating party expects, and + the contract can reject the connection or accept it and return the protocol version it will communicate with. + Implementing this (contract selects a version, not just the relayer) requires that we support + [ADR 025](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-025-ibc-passive-channels.md). + TODO: check with Agoric and cwgoes to upstream any Cosmos SDK changes so this can work out of the box. +3. `OnChanOpened` is called on the contract for both `OnChanOpenAck` and `OnChanOpenConfirm` containing + the final version string (counterparty version). This gives a chance to abort the process + if we realize this doesn't work. Or save the info (we may need to define this channel uses an older version + of the protocol for example). +4. `OnChanClosed` is called on both sides if the channel is closed for any reason, allowing them to + perform any cleanup. This will be followed by `IBCPacketTimeout` callbacks for all the in-progress + packets that were not processed before it closed, as well as all pending acks (pending the relayer + to provide that). + +We require the following callbacks on the contract + +* `OnChanNegotiate` - called on the initiating side on `OnChanOpenInit` and on receiving end for `OnChanOpenTry`. + @alpe: does it make sense to use the same shape for both of these? Rather than `CounterPartyVersion`, they would + have `ProposedVersion`, but otherwise the same logic. +* `OnChanOpened` - called on both sides after the initial 2 steps have passed to confirm the version used +* `OnChanClosed` - this is called when an existing channel is closed for any reason + +### Queries + +We may want to expose some basic queries of IBC State to the contract. +We should check if this is useful to the contract and if it opens up +any possible DoS: + +* `GetPortID` - return PortID given a contract address +* `ListChannels` - return a list of all (portID, channelID) pairs + that are bound to a given port. +* `ListPendingPackets` - given a (portID, channelID) identifier, return all packets + in that channel, that have been sent by this chain, but for which no acknowledgement + or timeout has yet been received +* `ListPendingAcknowledgements` - given a (portID, channelID) identifier, return all packets + in that channel, that have been received and processed by this chain, but for which + we have no proof the acknowledgement has been relayed +* `GetCounterparty` - given a local (portID, channelID) identifier, it will look up + what (portID, channelID) are bound to the remote end of the channel. + +## Contract Details + +Here we map out the workflow with the exact arguments passed with those calls +from the Go side (which we will use with our mock), and then a +proposal for multiplexing this over fewer wasm exports (define some rust types) + +Messages: + +```go +package messages + +type IBCSendMsg struct { + // This is our contract-local ID + ChannelID string + Msg []byte + // optional fields (or do we need exactly/at least one of these?) + TimeoutHeight uint64 + TimeoutTimestamp uint64 +} + +type IBCCloseChannel struct { + ChannelID string +} + +// "Versions must be strings but and implement any versioning structure..." +// https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation +// Use the same approach here +type Version string +``` + +Packet callbacks: + +```go +package packets + +// for reference: this is more like what we pass to go-cosmwasm +// func (c *mockContract) OnReceive(params cosmwasm2.Env, msg []byte, store prefix.Store, api cosmwasm.GoAPI, +// querier keeper.QueryHandler, meter sdk.GasMeter, gas uint64) (*cosmwasm2.OnReceiveIBCResponse, uint64, error) {} +// below is how we want to expose it in x/wasm: + +// IBCRecvPacket is called when we receive a packet sent from the other end of a channel +// The response bytes listed here will be returned to the caller as "result" in IBCPacketAck +// What do we do with error? +// +// If we were to assume/enforce an envelope, then we could wrap response/error into the acknowledge packet, +// but we delegated that encoding to the contract +func IBCRecvPacket(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, env IBCPacketInfo, msg []byte) + (response []byte, err error) {} + +// how to handle error here? if we push it up the ibc stack and fail the transaction (normal handling), +// the packet may be posted again and again. just log and ignore failures here? what does a failure even mean? +// only realistic one I can imagine is OutOfGas (panic) to retry with higher gas limit. +// +// if there any point in returning a response, what does it mean? +func IBCPacketAck(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, env IBCPacketInfo, + originalMsg []byte, result []byte) error {} + +// same question as for IBCPacketAck +func IBCPacketDropped(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, env IBCPacketInfo, + originalMsg []byte, errorMsg string) error {} + +// do we need/want all this info? +type IBCPacketInfo struct { + // local id for the Channel packet was sent/received on + ChannelID string + + // sequence for the packet (will already be enforced in order if ORDERED channel) + Sequence uint64 + + // Note: Timeout if guaranteed ONLY to be exceeded iff we are processing IBCPacketDropped + // otherwise, this is just interesting metadata + + // block height after which the packet times out + TimeoutHeight uint64 + // block timestamp (in nanoseconds) after which the packet times out + TimeoutTimestamp uint64 +} +``` + +Channel Lifecycle: + +```go +package lifecycle + +// if this returns error, we reject the channel opening +// otherwise response has the versions we accept +// +// It is provided the full ChannelInfo being proposed to do any needed checks +func OnChanNegotiate(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, request ChannelInfo) + (version Version, err error) {} + +// This is called with the full ChannelInfo once the other side has agreed. +// An error here will still abort the handshake process. (so you can double check the order/version here) +// +// The main purpose is to allow the contract to set up any internal state knowing the channel was established, +// and keep a registry with that ChannelID +func OnChanOpened(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, request ChannelInfo) error {} + +// This is called when the channel is closed for any reason +// TODO: any meaning to return an error here? we cannot abort closing a channel +func OnChanClosed(ctx sdk.Context, k *wasm.Keeper, contractAddress sdk.AccAddress, request ChannelClosedInfo) error {} + +type ChannelInfo struct { + // key info to enforce (error if not what is expected) + Order channeltypes.Order + // The proposed version. This may come from the relayer, from the initiating contract, or the responding contract. + // In any case, this is the currently agreed upon version to use and if there is disagreement, the contract should + // propose another one (if possible in return value), or return an error + ProposedVersion Version + // local id for the Channel that is being initiated + ChannelID string + // these two are taken from channeltypes.Counterparty + RemotePortID string + RemoteChannelID string +} + +type ChannelClosedInfo struct { + // local id for the Channel that is being shut down + ChannelID string +} +``` + +Queries: + +These are callbacks that the contract can make, calling into a QueryPlugin. +The general type definition for a `QueryPlugin` is +`func(ctx sdk.Context, request *wasmTypes.IBCQuery) ([]byte, error)`. +All other info (like the contract address we are querying for) must be passed in +from the contract (which knows it's own address). + +Here we just defined the request and response types (which will be serialized into `[]byte`) + +```go +package queries + +type QueryPort struct { + ContractAddress string +} + +type QueryPortResponse struct { + PortID string +} + +type QueryChannels struct { + // exactly one of these must be set. ContractAddress is a shortcut to save the Contract->PortID mapping + PortID string + ContractAddress string +} + +type QueryChannelsResponse struct { + ChannelIDs []ChannelMetadata +} + +type ChannelMetadata struct { + // Local portID, channelID is our unique identifier + PortID string + ChannelID string + RemotePortID string + Order channeltypes.Order + Verson Version +} + +type QueryPendingPackets struct { + // Always required + ChannelID string + + // exactly one of these must be set. ContractAddress is a shortcut to save the Contract->PortID mapping + PortID string + ContractAddress string +} + +type QueryPendingPacketsResponse struct { + Packets []PacketMetadata +} + +type PacketMetadata struct { + // The original (serialized) message we sent + Msg []byte + + Sequence uint64 + // block height after which the packet times out + TimeoutHeight uint64 + // block timestamp (in nanoseconds) after which the packet times out + TimeoutTimestamp uint64 +} + +type QueryPendingAcknowlegdements struct { + // Always required + ChannelID string + + // exactly one of these must be set. ContractAddress is a shortcut to save the Contract->PortID mapping + PortID string + ContractAddress string +} + +type QueryPendingPacketsResponse struct { + // Do we need another struct for the metadata? + Packets []PacketMetadata +} + + +type QueryCounterparty struct { + // Always required + ChannelID string + + // exactly one of these must be set. ContractAddress is a shortcut to save the Contract->PortID mapping + PortID string + ContractAddress string +} + +// lists (port, channel) on the counterparty for our local channel +type QueryCounterpartyResponse struct { + PortID string + ChannelID string +} +``` + +### Contract (Wasm) entrypoints + +**TODO** + +## Future Ideas + +Here are some ideas we may add in the future + +### Dynamic Ports and Channels + +* multiple ports per contract +* elastic ports that can be assigned to different contracts +* transfer of channels to another contract + +This is inspired by the Agoric design, but also adds considerable complexity to both the `x/wasm` +implementation as well as the correctness reasoning of any given contract. This will not be +available in the first version of our "IBC Enabled contracts", but we can consider it for later, +if there are concrete user cases that would significantly benefit from this added complexity. + +### Add multihop support + +Once the ICS and IBC specs fully establish how multihop packets work, we should add support for that. +Both on setting up the routes with OpenChannel, as well as acting as an intermediate relayer (if that is possible) + +## Rejected Ideas + +### One Port per Module + +We decided on "one port per contract", especially after the IBC team raised +the max length on port names to allow `wasm-` to be a valid port. +Here are the arguments for "one port for x/wasm" vs "one port per contract". Here +was an alternate proposal: + +In this approach, the `x/wasm` module just binds one port to handle all +modules. This can be well defined name like `wasm`. Since we always +have `(ChannelID, PortID)` for routing messages, we can reuse one port +for all contracts as long as we have a clear way to map the `ChannelID` +to a specific contract when it is being established. + + +* On genesis we bind the port `wasm` for all communication with the `x/wasm` + module. +* The *Port* is fully owned by `x/wasm` +* Each *Channel* is fully owned by one contract. +* `x/wasm` only accepts *ORDERED Channels* for simplicity of contract + correctness. + +To clarify: + +* When a *Channel* is being established with port `wasm`, the + `x/wasm.Keeper` must be able to identify for which contract this + is destined. **how to do so**?? + * One idea: the channel name must be the contract address. This means + (`wasm`, `cosmos13d...`) will map to the given contract in the wasm module. + The problem with this is that if two contracts from chainA want to + connect to the same contracts on chainB, they will want to claim the + same *ChannelID* and *PortID*. Not sure how to differentiate multiple + parties in this way. + * Other ideas: have a special field we send on `OnChanOpenInit` that + specifies the destination contract, and allow any *ChannelID*. + However, looking at [`OnChanOpenInit` function signature](https://docs.cosmos.network/master/ibc/custom.html#implement-ibcmodule-interface-and-callbacks), + I don't see a place to put this extra info, without abusing the version field, + which is a [specified field](https://docs.cosmos.network/master/ibc/custom.html#channel-handshake-version-negotiation): + ``` + Versions must be strings but can implement any versioning structure. + If your application plans to have linear releases then semantic versioning is recommended. + ... + Valid version selection includes selecting a compatible version identifier with a subset + of features supported by your application for that version. + ... + ICS20 currently implements basic string matching with a + single supported version. + ``` \ No newline at end of file diff --git a/x/wasm/alias.go b/x/wasm/alias.go index 3636c1e6fa..ba71991763 100644 --- a/x/wasm/alias.go +++ b/x/wasm/alias.go @@ -43,7 +43,8 @@ const ( var ( // functions aliases - RegisterCodec = types.RegisterCodec + RegisterCodec = types.RegisterLegacyAminoCodec + RegisterInterfaces = types.RegisterInterfaces ValidateGenesis = types.ValidateGenesis ConvertToProposals = types.ConvertToProposals GetCodeKey = types.GetCodeKey @@ -66,16 +67,16 @@ var ( EncodeStakingMsg = keeper.EncodeStakingMsg EncodeWasmMsg = keeper.EncodeWasmMsg NewKeeper = keeper.NewKeeper - NewQuerier = keeper.NewQuerier + NewLegacyQuerier = keeper.NewLegacyQuerier DefaultQueryPlugins = keeper.DefaultQueryPlugins BankQuerier = keeper.BankQuerier NoCustomQuerier = keeper.NoCustomQuerier StakingQuerier = keeper.StakingQuerier WasmQuerier = keeper.WasmQuerier - MakeTestCodec = keeper.MakeTestCodec CreateTestInput = keeper.CreateTestInput TestHandler = keeper.TestHandler NewWasmProposalHandler = keeper.NewWasmProposalHandler + NewQuerier = keeper.NewQuerier // variable aliases ModuleCdc = types.ModuleCdc @@ -114,6 +115,8 @@ type ( ContractInfo = types.ContractInfo CreatedAt = types.AbsoluteTxPosition Config = types.WasmConfig + ContractInfoWithAddress = types.ContractInfoWithAddress + CodeInfoResponse = types.CodeInfoResponse MessageHandler = keeper.MessageHandler BankEncoder = keeper.BankEncoder CustomEncoder = keeper.CustomEncoder @@ -121,9 +124,6 @@ type ( WasmEncoder = keeper.WasmEncoder MessageEncoders = keeper.MessageEncoders Keeper = keeper.Keeper - ContractInfoWithAddress = keeper.ContractInfoWithAddress - GetCodeResponse = keeper.GetCodeResponse - ListCodeResponse = keeper.ListCodeResponse QueryHandler = keeper.QueryHandler CustomQuerier = keeper.CustomQuerier QueryPlugins = keeper.QueryPlugins diff --git a/x/wasm/client/cli/gov_tx.go b/x/wasm/client/cli/gov_tx.go index 56cb7eff9c..058b117525 100644 --- a/x/wasm/client/cli/gov_tx.go +++ b/x/wasm/client/cli/gov_tx.go @@ -1,15 +1,11 @@ package cli import ( - "bufio" - "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" "github.com/cosmos/cosmos-sdk/x/gov/client/cli" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/pkg/errors" @@ -17,17 +13,19 @@ import ( "github.com/spf13/viper" ) -func ProposalStoreCodeCmd(cdc *codec.Codec) *cobra.Command { +func ProposalStoreCodeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "wasm-store [wasm file] --source [source] --builder [builder] --title [text] --description [text] --run-as [address]", Short: "Submit a wasm binary proposal", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } - src, err := parseStoreCodeArgs(args, cliCtx) + src, err := parseStoreCodeArgs(args, clientCtx) if err != nil { return err } @@ -39,10 +37,8 @@ func ProposalStoreCodeCmd(cdc *codec.Codec) *cobra.Command { return errors.Wrap(err, "run-as") } content := types.StoreCodeProposal{ - WasmProposal: types.WasmProposal{ - Title: viper.GetString(cli.FlagTitle), - Description: viper.GetString(cli.FlagDescription), - }, + Title: viper.GetString(cli.FlagTitle), + Description: viper.GetString(cli.FlagDescription), RunAs: runAsAddr, WASMByteCode: src.WASMByteCode, Source: src.Source, @@ -54,13 +50,15 @@ func ProposalStoreCodeCmd(cdc *codec.Codec) *cobra.Command { if err != nil { return err } - - msg := govtypes.NewMsgSubmitProposal(content, deposit, cliCtx.GetFromAddress()) + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) + if err != nil { + return err + } if err = msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } @@ -76,21 +74,23 @@ func ProposalStoreCodeCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") cmd.Flags().String(cli.FlagProposal, "", "Proposal file path (if this path is given, other proposal flags are ignored)") // type values must match the "ProposalHandler" "routes" in cli - cmd.Flags().String(flagProposalType, "", "Type of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") + cmd.Flags().String(flagProposalType, "", "Permission of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") return cmd } -func ProposalInstantiateContractCmd(cdc *codec.Codec) *cobra.Command { +func ProposalInstantiateContractCmd() *cobra.Command { cmd := &cobra.Command{ Use: "instantiate-contract [code_id_int64] [json_encoded_init_args] --label [text] --title [text] --description [text] --run-as [address] --admin [address,optional] --amount [coins,optional]", Short: "Submit an instantiate wasm contract proposal", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } - src, err := parseInstantiateArgs(args, cliCtx) + src, err := parseInstantiateArgs(args, clientCtx) if err != nil { return err } @@ -102,16 +102,14 @@ func ProposalInstantiateContractCmd(cdc *codec.Codec) *cobra.Command { return errors.Wrap(err, "creator") } content := types.InstantiateContractProposal{ - WasmProposal: types.WasmProposal{ - Title: viper.GetString(cli.FlagTitle), - Description: viper.GetString(cli.FlagDescription), - }, - RunAs: creator, - Admin: src.Admin, - CodeID: src.CodeID, - Label: src.Label, - InitMsg: src.InitMsg, - InitFunds: src.InitFunds, + Title: viper.GetString(cli.FlagTitle), + Description: viper.GetString(cli.FlagDescription), + RunAs: creator, + Admin: src.Admin, + CodeID: src.CodeID, + Label: src.Label, + InitMsg: src.InitMsg, + InitFunds: src.InitFunds, } deposit, err := sdk.ParseCoins(viper.GetString(cli.FlagDeposit)) @@ -119,12 +117,15 @@ func ProposalInstantiateContractCmd(cdc *codec.Codec) *cobra.Command { return err } - msg := govtypes.NewMsgSubmitProposal(content, deposit, cliCtx.GetFromAddress()) + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) + if err != nil { + return err + } if err = msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") @@ -138,21 +139,23 @@ func ProposalInstantiateContractCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") cmd.Flags().String(cli.FlagProposal, "", "Proposal file path (if this path is given, other proposal flags are ignored)") // type values must match the "ProposalHandler" "routes" in cli - cmd.Flags().String(flagProposalType, "", "Type of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") + cmd.Flags().String(flagProposalType, "", "Permission of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") return cmd } -func ProposalMigrateContractCmd(cdc *codec.Codec) *cobra.Command { +func ProposalMigrateContractCmd() *cobra.Command { cmd := &cobra.Command{ Use: "migrate-contract [contract_addr_bech32] [new_code_id_int64] [json_encoded_migration_args]", Short: "Submit a migrate wasm contract to a new code version proposal", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } - src, err := parseMigrateContractArgs(args, cliCtx) + src, err := parseMigrateContractArgs(args, clientCtx) if err != nil { return err } @@ -166,14 +169,12 @@ func ProposalMigrateContractCmd(cdc *codec.Codec) *cobra.Command { } content := types.MigrateContractProposal{ - WasmProposal: types.WasmProposal{ - Title: viper.GetString(cli.FlagTitle), - Description: viper.GetString(cli.FlagDescription), - }, - Contract: src.Contract, - CodeID: src.CodeID, - MigrateMsg: src.MigrateMsg, - RunAs: runAs, + Title: viper.GetString(cli.FlagTitle), + Description: viper.GetString(cli.FlagDescription), + Contract: src.Contract, + CodeID: src.CodeID, + MigrateMsg: src.MigrateMsg, + RunAs: runAs, } deposit, err := sdk.ParseCoins(viper.GetString(cli.FlagDeposit)) @@ -181,12 +182,15 @@ func ProposalMigrateContractCmd(cdc *codec.Codec) *cobra.Command { return err } - msg := govtypes.NewMsgSubmitProposal(content, deposit, cliCtx.GetFromAddress()) + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) + if err != nil { + return err + } if err = msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } cmd.Flags().String(flagRunAs, "", "The address that is passed as sender to the contract on proposal execution") @@ -197,32 +201,32 @@ func ProposalMigrateContractCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") cmd.Flags().String(cli.FlagProposal, "", "Proposal file path (if this path is given, other proposal flags are ignored)") // type values must match the "ProposalHandler" "routes" in cli - cmd.Flags().String(flagProposalType, "", "Type of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") + cmd.Flags().String(flagProposalType, "", "Permission of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") return cmd } -func ProposalUpdateContractAdminCmd(cdc *codec.Codec) *cobra.Command { +func ProposalUpdateContractAdminCmd() *cobra.Command { cmd := &cobra.Command{ Use: "set-contract-admin [contract_addr_bech32] [new_admin_addr_bech32]", Short: "Submit a new admin for a contract proposal", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } - src, err := parseUpdateContractAdminArgs(args, cliCtx) + src, err := parseUpdateContractAdminArgs(args, clientCtx) if err != nil { return err } content := types.UpdateAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: viper.GetString(cli.FlagTitle), - Description: viper.GetString(cli.FlagDescription), - }, - Contract: src.Contract, - NewAdmin: src.NewAdmin, + Title: viper.GetString(cli.FlagTitle), + Description: viper.GetString(cli.FlagDescription), + Contract: src.Contract, + NewAdmin: src.NewAdmin, } deposit, err := sdk.ParseCoins(viper.GetString(cli.FlagDeposit)) @@ -230,12 +234,15 @@ func ProposalUpdateContractAdminCmd(cdc *codec.Codec) *cobra.Command { return err } - msg := govtypes.NewMsgSubmitProposal(content, deposit, cliCtx.GetFromAddress()) + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) + if err != nil { + return err + } if err = msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } // proposal flags @@ -244,19 +251,21 @@ func ProposalUpdateContractAdminCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") cmd.Flags().String(cli.FlagProposal, "", "Proposal file path (if this path is given, other proposal flags are ignored)") // type values must match the "ProposalHandler" "routes" in cli - cmd.Flags().String(flagProposalType, "", "Type of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") + cmd.Flags().String(flagProposalType, "", "Permission of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") return cmd } -func ProposalClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { +func ProposalClearContractAdminCmd() *cobra.Command { cmd := &cobra.Command{ Use: "clear-contract-admin [contract_addr_bech32]", Short: "Submit a clear admin for a contract to prevent further migrations proposal", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } contractAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -264,11 +273,9 @@ func ProposalClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { } content := types.ClearAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: viper.GetString(cli.FlagTitle), - Description: viper.GetString(cli.FlagDescription), - }, - Contract: contractAddr, + Title: viper.GetString(cli.FlagTitle), + Description: viper.GetString(cli.FlagDescription), + Contract: contractAddr, } deposit, err := sdk.ParseCoins(viper.GetString(cli.FlagDeposit)) @@ -276,12 +283,15 @@ func ProposalClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { return err } - msg := govtypes.NewMsgSubmitProposal(content, deposit, cliCtx.GetFromAddress()) + msg, err := govtypes.NewMsgSubmitProposal(&content, deposit, clientCtx.GetFromAddress()) + if err != nil { + return err + } if err = msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) }, } // proposal flags @@ -290,6 +300,6 @@ func ProposalClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(cli.FlagDeposit, "", "Deposit of proposal") cmd.Flags().String(cli.FlagProposal, "", "Proposal file path (if this path is given, other proposal flags are ignored)") // type values must match the "ProposalHandler" "routes" in cli - cmd.Flags().String(flagProposalType, "", "Type of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") + cmd.Flags().String(flagProposalType, "", "Permission of proposal, types: store-code/instantiate/migrate/update-admin/clear-admin/text/parameter_change/software_upgrade") return cmd } diff --git a/x/wasm/client/cli/new_tx.go b/x/wasm/client/cli/new_tx.go index fd47930901..e6a2879f5d 100644 --- a/x/wasm/client/cli/new_tx.go +++ b/x/wasm/client/cli/new_tx.go @@ -1,44 +1,42 @@ package cli import ( - "bufio" "strconv" "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" "github.com/spf13/cobra" ) // MigrateContractCmd will migrate a contract to a new code version -func MigrateContractCmd(cdc *codec.Codec) *cobra.Command { +func MigrateContractCmd() *cobra.Command { cmd := &cobra.Command{ Use: "migrate [contract_addr_bech32] [new_code_id_int64] [json_encoded_migration_args]", Short: "Migrate a wasm contract to a new code version", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) - msg, err := parseMigrateContractArgs(args, cliCtx) + msg, err := parseMigrateContractArgs(args, clientCtx) if err != nil { return err } if err := msg.ValidateBasic(); err != nil { return nil } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } + flags.AddTxFlagsToCmd(cmd) return cmd } -func parseMigrateContractArgs(args []string, cliCtx context.CLIContext) (types.MsgMigrateContract, error) { +func parseMigrateContractArgs(args []string, cliCtx client.Context) (types.MsgMigrateContract, error) { contractAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return types.MsgMigrateContract{}, sdkerrors.Wrap(err, "contract") @@ -62,30 +60,30 @@ func parseMigrateContractArgs(args []string, cliCtx context.CLIContext) (types.M } // UpdateContractAdminCmd sets an new admin for a contract -func UpdateContractAdminCmd(cdc *codec.Codec) *cobra.Command { +func UpdateContractAdminCmd() *cobra.Command { cmd := &cobra.Command{ Use: "set-contract-admin [contract_addr_bech32] [new_admin_addr_bech32]", Short: "Set new admin for a contract", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) - msg, err := parseUpdateContractAdminArgs(args, cliCtx) + msg, err := parseUpdateContractAdminArgs(args, clientCtx) if err != nil { return err } if err := msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } + flags.AddTxFlagsToCmd(cmd) return cmd } -func parseUpdateContractAdminArgs(args []string, cliCtx context.CLIContext) (types.MsgUpdateAdmin, error) { +func parseUpdateContractAdminArgs(args []string, cliCtx client.Context) (types.MsgUpdateAdmin, error) { contractAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { return types.MsgUpdateAdmin{}, sdkerrors.Wrap(err, "contract") @@ -104,15 +102,14 @@ func parseUpdateContractAdminArgs(args []string, cliCtx context.CLIContext) (typ } // ClearContractAdminCmd clears an admin for a contract -func ClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { +func ClearContractAdminCmd() *cobra.Command { cmd := &cobra.Command{ Use: "clear-contract-admin [contract_addr_bech32]", Short: "Clears admin for a contract to prevent further migrations", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) contractAddr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -120,14 +117,15 @@ func ClearContractAdminCmd(cdc *codec.Codec) *cobra.Command { } msg := types.MsgClearAdmin{ - Sender: cliCtx.GetFromAddress(), + Sender: clientCtx.GetFromAddress(), Contract: contractAddr, } if err := msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } + flags.AddTxFlagsToCmd(cmd) return cmd } diff --git a/x/wasm/client/cli/query.go b/x/wasm/client/cli/query.go index 9c562be106..6915902180 100644 --- a/x/wasm/client/cli/query.go +++ b/x/wasm/client/cli/query.go @@ -9,21 +9,16 @@ import ( "io/ioutil" "strconv" - flag "github.com/spf13/pflag" - - "github.com/spf13/cobra" - + "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" - - "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" - "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/spf13/cobra" + flag "github.com/spf13/pflag" ) -func GetQueryCmd(cdc *codec.Codec) *cobra.Command { +func GetQueryCmd() *cobra.Command { queryCmd := &cobra.Command{ Use: types.ModuleName, Short: "Querying commands for the wasm module", @@ -31,47 +26,57 @@ func GetQueryCmd(cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - queryCmd.AddCommand(flags.GetCommands( - GetCmdListCode(cdc), - GetCmdListContractByCode(cdc), - GetCmdQueryCode(cdc), - GetCmdGetContractInfo(cdc), - GetCmdGetContractHistory(cdc), - GetCmdGetContractState(cdc), - )...) + queryCmd.AddCommand( + GetCmdListCode(), + GetCmdListContractByCode(), + GetCmdQueryCode(), + GetCmdGetContractInfo(), + GetCmdGetContractHistory(), + GetCmdGetContractState(), + ) return queryCmd } // GetCmdListCode lists all wasm code uploaded -func GetCmdListCode(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdListCode() *cobra.Command { + cmd := &cobra.Command{ Use: "list-code", Short: "List all wasm bytecode on the chain", Long: "List all wasm bytecode on the chain", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } route := fmt.Sprintf("custom/%s/%s", types.QuerierRoute, keeper.QueryListCode) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } - fmt.Println(string(res)) + fmt.Println(string(res)) // TODO: here and others: handle output format proper. See clientCtx.PrintOutput(string(res)) return nil }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } // GetCmdListContractByCode lists all wasm code uploaded for given code id -func GetCmdListContractByCode(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdListContractByCode() *cobra.Command { + cmd := &cobra.Command{ Use: "list-contract-by-code [code_id]", Short: "List wasm all bytecode on the chain for given code id", Long: "List wasm all bytecode on the chain for given code id", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } codeID, err := strconv.ParseUint(args[0], 10, 64) if err != nil { @@ -79,7 +84,7 @@ func GetCmdListContractByCode(cdc *codec.Codec) *cobra.Command { } route := fmt.Sprintf("custom/%s/%s/%d", types.QuerierRoute, keeper.QueryListContractByCode, codeID) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } @@ -87,17 +92,23 @@ func GetCmdListContractByCode(cdc *codec.Codec) *cobra.Command { return nil }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } // GetCmdQueryCode returns the bytecode for a given contract -func GetCmdQueryCode(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdQueryCode() *cobra.Command { + cmd := &cobra.Command{ Use: "code [code_id] [output filename]", Short: "Downloads wasm bytecode for given code id", Long: "Downloads wasm bytecode for given code id", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } codeID, err := strconv.ParseUint(args[0], 10, 64) if err != nil { @@ -105,14 +116,14 @@ func GetCmdQueryCode(cdc *codec.Codec) *cobra.Command { } route := fmt.Sprintf("custom/%s/%s/%d", types.QuerierRoute, keeper.QueryGetCode, codeID) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } if len(res) == 0 { return fmt.Errorf("contract not found") } - var code keeper.GetCodeResponse + var code types.QueryCodeResponse err = json.Unmarshal(res, &code) if err != nil { return err @@ -126,17 +137,23 @@ func GetCmdQueryCode(cdc *codec.Codec) *cobra.Command { return ioutil.WriteFile(args[1], code.Data, 0644) }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } // GetCmdGetContractInfo gets details about a given contract -func GetCmdGetContractInfo(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdGetContractInfo() *cobra.Command { + cmd := &cobra.Command{ Use: "contract [bech32_address]", Short: "Prints out metadata of a contract given its address", Long: "Prints out metadata of a contract given its address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -144,7 +161,7 @@ func GetCmdGetContractInfo(cdc *codec.Codec) *cobra.Command { } route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContract, addr.String()) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } @@ -152,10 +169,12 @@ func GetCmdGetContractInfo(cdc *codec.Codec) *cobra.Command { return nil }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } // GetCmdGetContractState dumps full internal state of a given contract -func GetCmdGetContractState(cdc *codec.Codec) *cobra.Command { +func GetCmdGetContractState() *cobra.Command { cmd := &cobra.Command{ Use: "contract-state", Short: "Querying commands for the wasm module", @@ -163,23 +182,27 @@ func GetCmdGetContractState(cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - cmd.AddCommand(flags.GetCommands( - GetCmdGetContractStateAll(cdc), - GetCmdGetContractStateRaw(cdc), - GetCmdGetContractStateSmart(cdc), - )...) + cmd.AddCommand( + GetCmdGetContractStateAll(), + GetCmdGetContractStateRaw(), + GetCmdGetContractStateSmart(), + ) return cmd } -func GetCmdGetContractStateAll(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdGetContractStateAll() *cobra.Command { + cmd := &cobra.Command{ Use: "all [bech32_address]", Short: "Prints out all internal state of a contract given its address", Long: "Prints out all internal state of a contract given its address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -187,7 +210,7 @@ func GetCmdGetContractStateAll(cdc *codec.Codec) *cobra.Command { } route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } @@ -195,17 +218,23 @@ func GetCmdGetContractStateAll(cdc *codec.Codec) *cobra.Command { return nil }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } -func GetCmdGetContractStateRaw(cdc *codec.Codec) *cobra.Command { +func GetCmdGetContractStateRaw() *cobra.Command { decoder := newArgDecoder(hex.DecodeString) cmd := &cobra.Command{ Use: "raw [bech32_address] [key]", Short: "Prints out internal state for key of a contract given its address", Long: "Prints out internal state for of a contract given its address", Args: cobra.ExactArgs(2), - RunE: func(_ *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -216,7 +245,7 @@ func GetCmdGetContractStateRaw(cdc *codec.Codec) *cobra.Command { return err } route := fmt.Sprintf("custom/%s/%s/%s/%s", types.QuerierRoute, keeper.QueryGetContractState, addr.String(), keeper.QueryMethodContractStateRaw) - res, _, err := cliCtx.QueryWithData(route, queryData) + res, _, err := clientCtx.QueryWithData(route, queryData) if err != nil { return err } @@ -225,10 +254,11 @@ func GetCmdGetContractStateRaw(cdc *codec.Codec) *cobra.Command { }, } decoder.RegisterFlags(cmd.PersistentFlags(), "key argument") + flags.AddQueryFlagsToCmd(cmd) return cmd } -func GetCmdGetContractStateSmart(cdc *codec.Codec) *cobra.Command { +func GetCmdGetContractStateSmart() *cobra.Command { decoder := newArgDecoder(asciiDecodeString) cmd := &cobra.Command{ @@ -236,8 +266,12 @@ func GetCmdGetContractStateSmart(cdc *codec.Codec) *cobra.Command { Short: "Calls contract with given address with query data and prints the returned result", Long: "Calls contract with given address with query data and prints the returned result", Args: cobra.ExactArgs(2), - RunE: func(_ *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + RunE: func(cmd *cobra.Command, args []string) error { + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -256,7 +290,7 @@ func GetCmdGetContractStateSmart(cdc *codec.Codec) *cobra.Command { if !json.Valid(queryData) { return errors.New("query data must be json") } - res, _, err := cliCtx.QueryWithData(route, queryData) + res, _, err := clientCtx.QueryWithData(route, queryData) if err != nil { return err } @@ -265,18 +299,23 @@ func GetCmdGetContractStateSmart(cdc *codec.Codec) *cobra.Command { }, } decoder.RegisterFlags(cmd.PersistentFlags(), "query argument") + flags.AddQueryFlagsToCmd(cmd) return cmd } // GetCmdGetContractHistory prints the code history for a given contract -func GetCmdGetContractHistory(cdc *codec.Codec) *cobra.Command { - return &cobra.Command{ +func GetCmdGetContractHistory() *cobra.Command { + cmd := &cobra.Command{ Use: "contract-history [bech32_address]", Short: "Prints out the code history for a contract given its address", Long: "Prints out the code history for a contract given its address", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cliCtx := context.NewCLIContext().WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadQueryCommandFlags(clientCtx, cmd.Flags()) + if err != nil { + return err + } addr, err := sdk.AccAddressFromBech32(args[0]) if err != nil { @@ -284,7 +323,7 @@ func GetCmdGetContractHistory(cdc *codec.Codec) *cobra.Command { } route := fmt.Sprintf("custom/%s/%s/%s", types.QuerierRoute, keeper.QueryContractHistory, addr.String()) - res, _, err := cliCtx.Query(route) + res, _, err := clientCtx.Query(route) if err != nil { return err } @@ -292,6 +331,8 @@ func GetCmdGetContractHistory(cdc *codec.Codec) *cobra.Command { return nil }, } + flags.AddQueryFlagsToCmd(cmd) + return cmd } type argumentDecoder struct { diff --git a/x/wasm/client/cli/tx.go b/x/wasm/client/cli/tx.go index 0db2862fad..c14a7f37e8 100644 --- a/x/wasm/client/cli/tx.go +++ b/x/wasm/client/cli/tx.go @@ -1,25 +1,19 @@ package cli import ( - "bufio" "fmt" "io/ioutil" "strconv" - "github.com/spf13/cobra" - "github.com/spf13/viper" - + wasmUtils "github.com/CosmWasm/wasmd/x/wasm/client/utils" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/context" "github.com/cosmos/cosmos-sdk/client/flags" - "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - - wasmUtils "github.com/CosmWasm/wasmd/x/wasm/client/utils" - "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/spf13/cobra" + "github.com/spf13/viper" ) const ( @@ -35,7 +29,7 @@ const ( ) // GetTxCmd returns the transaction commands for this module -func GetTxCmd(cdc *codec.Codec) *cobra.Command { +func GetTxCmd() *cobra.Command { txCmd := &cobra.Command{ Use: types.ModuleName, Short: "Wasm transaction subcommands", @@ -43,37 +37,35 @@ func GetTxCmd(cdc *codec.Codec) *cobra.Command { SuggestionsMinimumDistance: 2, RunE: client.ValidateCmd, } - txCmd.AddCommand(flags.PostCommands( - StoreCodeCmd(cdc), - InstantiateContractCmd(cdc), - ExecuteContractCmd(cdc), - MigrateContractCmd(cdc), - UpdateContractAdminCmd(cdc), - ClearContractAdminCmd(cdc), - )...) + txCmd.AddCommand( + StoreCodeCmd(), + InstantiateContractCmd(), + ExecuteContractCmd(), + MigrateContractCmd(), + UpdateContractAdminCmd(), + ClearContractAdminCmd(), + ) return txCmd } // StoreCodeCmd will upload code to be reused. -func StoreCodeCmd(cdc *codec.Codec) *cobra.Command { +func StoreCodeCmd() *cobra.Command { cmd := &cobra.Command{ Use: "store [wasm file] --source [source] --builder [builder]", Short: "Upload a wasm binary", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) - msg, err := parseStoreCodeArgs(args, cliCtx) + msg, err := parseStoreCodeArgs(args, clientCtx) if err != nil { return err } if err = msg.ValidateBasic(); err != nil { return err } - - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } @@ -81,11 +73,11 @@ func StoreCodeCmd(cdc *codec.Codec) *cobra.Command { cmd.Flags().String(flagBuilder, "", "A valid docker tag for the build system, optional") cmd.Flags().String(flagInstantiateByEverybody, "", "Everybody can instantiate a contract from the code, optional") cmd.Flags().String(flagInstantiateByAddress, "", "Only this address can instantiate a contract instance from the code, optional") - + flags.AddTxFlagsToCmd(cmd) return cmd } -func parseStoreCodeArgs(args []string, cliCtx context.CLIContext) (types.MsgStoreCode, error) { +func parseStoreCodeArgs(args []string, cliCtx client.Context) (types.MsgStoreCode, error) { wasm, err := ioutil.ReadFile(args[0]) if err != nil { return types.MsgStoreCode{}, err @@ -108,7 +100,7 @@ func parseStoreCodeArgs(args []string, cliCtx context.CLIContext) (types.MsgStor if err != nil { return types.MsgStoreCode{}, sdkerrors.Wrap(err, flagInstantiateByAddress) } - x := types.OnlyAddress.With(allowedAddr) + x := types.AccessTypeOnlyAddress.With(allowedAddr) perm = &x } else if everybody := viper.GetBool(flagInstantiateByEverybody); everybody { perm = &types.AllowEverybody @@ -126,34 +118,34 @@ func parseStoreCodeArgs(args []string, cliCtx context.CLIContext) (types.MsgStor } // InstantiateContractCmd will instantiate a contract from previously uploaded code. -func InstantiateContractCmd(cdc *codec.Codec) *cobra.Command { +func InstantiateContractCmd() *cobra.Command { cmd := &cobra.Command{ Use: "instantiate [code_id_int64] [json_encoded_init_args] --label [text] --admin [address,optional] --amount [coins,optional]", Short: "Instantiate a wasm contract", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) - msg, err := parseInstantiateArgs(args, cliCtx) + msg, err := parseInstantiateArgs(args, clientCtx) if err != nil { return err } if err := msg.ValidateBasic(); err != nil { return err } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } cmd.Flags().String(flagAmount, "", "Coins to send to the contract during instantiation") cmd.Flags().String(flagLabel, "", "A human-readable name for this contract in lists") cmd.Flags().String(flagAdmin, "", "Address of an admin") + flags.AddTxFlagsToCmd(cmd) return cmd } -func parseInstantiateArgs(args []string, cliCtx context.CLIContext) (types.MsgInstantiateContract, error) { +func parseInstantiateArgs(args []string, cliCtx client.Context) (types.MsgInstantiateContract, error) { // get the id of the code to instantiate codeID, err := strconv.ParseUint(args[0], 10, 64) if err != nil { @@ -195,15 +187,14 @@ func parseInstantiateArgs(args []string, cliCtx context.CLIContext) (types.MsgIn } // ExecuteContractCmd will instantiate a contract from previously uploaded code. -func ExecuteContractCmd(cdc *codec.Codec) *cobra.Command { +func ExecuteContractCmd() *cobra.Command { cmd := &cobra.Command{ Use: "execute [contract_addr_bech32] [json_encoded_send_args]", Short: "Execute a command on a wasm contract", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - inBuf := bufio.NewReader(cmd.InOrStdin()) - txBldr := auth.NewTxBuilderFromCLI(inBuf).WithTxEncoder(utils.GetTxEncoder(cdc)) - cliCtx := context.NewCLIContextWithInput(inBuf).WithCodec(cdc) + clientCtx := client.GetClientContextFromCmd(cmd) + clientCtx, err := client.ReadTxCommandFlags(clientCtx, cmd.Flags()) // get the id of the code to instantiate contractAddr, err := sdk.AccAddressFromBech32(args[0]) @@ -221,15 +212,16 @@ func ExecuteContractCmd(cdc *codec.Codec) *cobra.Command { // build and sign the transaction, then broadcast to Tendermint msg := types.MsgExecuteContract{ - Sender: cliCtx.GetFromAddress(), + Sender: clientCtx.GetFromAddress(), Contract: contractAddr, SentFunds: amount, Msg: []byte(execMsg), } - return utils.GenerateOrBroadcastMsgs(cliCtx, txBldr, []sdk.Msg{msg}) + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), &msg) }, } cmd.Flags().String(flagAmount, "", "Coins to send to the contract along with command") + flags.AddTxFlagsToCmd(cmd) return cmd } diff --git a/x/wasm/client/proposal_handler_test.go b/x/wasm/client/proposal_handler_test.go index e0ae0b9c5e..22ad1cf3b3 100644 --- a/x/wasm/client/proposal_handler_test.go +++ b/x/wasm/client/proposal_handler_test.go @@ -6,14 +6,13 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "testing" - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/client/context" - "github.com/cosmos/cosmos-sdk/codec" - sdk "github.com/cosmos/cosmos-sdk/types" - authvesting "github.com/cosmos/cosmos-sdk/x/auth/vesting" - "github.com/cosmos/cosmos-sdk/x/gov" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/simapp" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/gorilla/mux" "github.com/stretchr/testify/require" ) @@ -31,8 +30,15 @@ func TestGovRestHandlers(t *testing.T) { "fees": []dict{{"denom": "ustake", "amount": "1000000"}}, } ) - cdc := MakeCodec() - clientCtx := context.CLIContext{}.WithChainID("testing").WithCodec(cdc) + encodingConfig := simapp.MakeEncodingConfig() + clientCtx := client.Context{}. + WithJSONMarshaler(encodingConfig.Marshaler). + WithTxConfig(encodingConfig.TxConfig). + WithLegacyAmino(encodingConfig.Amino). + WithInput(os.Stdin). + WithAccountRetriever(authtypes.AccountRetriever{}). + WithBroadcastMode(flags.BroadcastBlock). + WithChainID("testing") // router setup as in gov/client/rest/tx.go propSubRtr := mux.NewRouter().PathPrefix("/gov/proposals").Subrouter() @@ -219,16 +225,3 @@ func TestGovRestHandlers(t *testing.T) { }) } } - -func MakeCodec() *codec.Codec { - var cdc = codec.New() - wasmtypes.RegisterCodec(cdc) - gov.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - codec.RegisterEvidences(cdc) - authvesting.RegisterCodec(cdc) - - return cdc.Seal() - -} diff --git a/x/wasm/client/rest/gov.go b/x/wasm/client/rest/gov.go index c274cafd61..15bbbf7352 100644 --- a/x/wasm/client/rest/gov.go +++ b/x/wasm/client/rest/gov.go @@ -5,12 +5,12 @@ import ( "net/http" "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" - "github.com/cosmos/cosmos-sdk/x/gov" govrest "github.com/cosmos/cosmos-sdk/x/gov/client/rest" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) type StoreCodeProposalJsonReq struct { @@ -32,12 +32,10 @@ type StoreCodeProposalJsonReq struct { InstantiatePermission *types.AccessConfig `json:"instantiate_permission" yaml:"instantiate_permission"` } -func (s StoreCodeProposalJsonReq) Content() gov.Content { - return types.StoreCodeProposal{ - WasmProposal: types.WasmProposal{ - Title: s.Title, - Description: s.Description, - }, +func (s StoreCodeProposalJsonReq) Content() govtypes.Content { + return &types.StoreCodeProposal{ + Title: s.Title, + Description: s.Description, RunAs: s.RunAs, WASMByteCode: s.WASMByteCode, Source: s.Source, @@ -55,12 +53,12 @@ func (s StoreCodeProposalJsonReq) GetBaseReq() rest.BaseReq { return s.BaseReq } -func StoreCodeProposalHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func StoreCodeProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_store_code", Handler: func(w http.ResponseWriter, r *http.Request) { var req StoreCodeProposalJsonReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } toStdTxResponse(cliCtx, w, req) @@ -86,15 +84,16 @@ type InstantiateProposalJsonReq struct { InitFunds sdk.Coins `json:"init_funds" yaml:"init_funds"` } -func (s InstantiateProposalJsonReq) Content() gov.Content { - return types.InstantiateContractProposal{ - WasmProposal: types.WasmProposal{Title: s.Title, Description: s.Description}, - RunAs: s.RunAs, - Admin: s.Admin, - CodeID: s.Code, - Label: s.Label, - InitMsg: s.InitMsg, - InitFunds: s.InitFunds, +func (s InstantiateProposalJsonReq) Content() govtypes.Content { + return &types.InstantiateContractProposal{ + Title: s.Title, + Description: s.Description, + RunAs: s.RunAs, + Admin: s.Admin, + CodeID: s.Code, + Label: s.Label, + InitMsg: s.InitMsg, + InitFunds: s.InitFunds, } } func (s InstantiateProposalJsonReq) GetProposer() sdk.AccAddress { @@ -107,12 +106,12 @@ func (s InstantiateProposalJsonReq) GetBaseReq() rest.BaseReq { return s.BaseReq } -func InstantiateProposalHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func InstantiateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_instantiate", Handler: func(w http.ResponseWriter, r *http.Request) { var req InstantiateProposalJsonReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } toStdTxResponse(cliCtx, w, req) @@ -136,13 +135,14 @@ type MigrateProposalJsonReq struct { RunAs sdk.AccAddress `json:"run_as" yaml:"run_as"` } -func (s MigrateProposalJsonReq) Content() gov.Content { - return types.MigrateContractProposal{ - WasmProposal: types.WasmProposal{Title: s.Title, Description: s.Description}, - Contract: s.Contract, - CodeID: s.Code, - MigrateMsg: s.MigrateMsg, - RunAs: s.RunAs, +func (s MigrateProposalJsonReq) Content() govtypes.Content { + return &types.MigrateContractProposal{ + Title: s.Title, + Description: s.Description, + Contract: s.Contract, + CodeID: s.Code, + MigrateMsg: s.MigrateMsg, + RunAs: s.RunAs, } } func (s MigrateProposalJsonReq) GetProposer() sdk.AccAddress { @@ -154,12 +154,12 @@ func (s MigrateProposalJsonReq) GetDeposit() sdk.Coins { func (s MigrateProposalJsonReq) GetBaseReq() rest.BaseReq { return s.BaseReq } -func MigrateProposalHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func MigrateProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_migrate", Handler: func(w http.ResponseWriter, r *http.Request) { var req MigrateProposalJsonReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } toStdTxResponse(cliCtx, w, req) @@ -180,11 +180,12 @@ type UpdateAdminJsonReq struct { Contract sdk.AccAddress `json:"contract" yaml:"contract"` } -func (s UpdateAdminJsonReq) Content() gov.Content { - return types.UpdateAdminProposal{ - WasmProposal: types.WasmProposal{Title: s.Title, Description: s.Description}, - Contract: s.Contract, - NewAdmin: s.NewAdmin, +func (s UpdateAdminJsonReq) Content() govtypes.Content { + return &types.UpdateAdminProposal{ + Title: s.Title, + Description: s.Description, + Contract: s.Contract, + NewAdmin: s.NewAdmin, } } func (s UpdateAdminJsonReq) GetProposer() sdk.AccAddress { @@ -196,12 +197,12 @@ func (s UpdateAdminJsonReq) GetDeposit() sdk.Coins { func (s UpdateAdminJsonReq) GetBaseReq() rest.BaseReq { return s.BaseReq } -func UpdateContractAdminProposalHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func UpdateContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_update_admin", Handler: func(w http.ResponseWriter, r *http.Request) { var req UpdateAdminJsonReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } toStdTxResponse(cliCtx, w, req) @@ -221,10 +222,11 @@ type ClearAdminJsonReq struct { Contract sdk.AccAddress `json:"contract" yaml:"contract"` } -func (s ClearAdminJsonReq) Content() gov.Content { - return types.ClearAdminProposal{ - WasmProposal: types.WasmProposal{Title: s.Title, Description: s.Description}, - Contract: s.Contract, +func (s ClearAdminJsonReq) Content() govtypes.Content { + return &types.ClearAdminProposal{ + Title: s.Title, + Description: s.Description, + Contract: s.Contract, } } func (s ClearAdminJsonReq) GetProposer() sdk.AccAddress { @@ -236,12 +238,12 @@ func (s ClearAdminJsonReq) GetDeposit() sdk.Coins { func (s ClearAdminJsonReq) GetBaseReq() rest.BaseReq { return s.BaseReq } -func ClearContractAdminProposalHandler(cliCtx context.CLIContext) govrest.ProposalRESTHandler { +func ClearContractAdminProposalHandler(cliCtx client.Context) govrest.ProposalRESTHandler { return govrest.ProposalRESTHandler{ SubRoute: "wasm_clear_admin", Handler: func(w http.ResponseWriter, r *http.Request) { var req ClearAdminJsonReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } toStdTxResponse(cliCtx, w, req) @@ -250,14 +252,18 @@ func ClearContractAdminProposalHandler(cliCtx context.CLIContext) govrest.Propos } type wasmProposalData interface { - Content() gov.Content + Content() govtypes.Content GetProposer() sdk.AccAddress GetDeposit() sdk.Coins GetBaseReq() rest.BaseReq } -func toStdTxResponse(cliCtx context.CLIContext, w http.ResponseWriter, data wasmProposalData) { - msg := gov.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), data.GetProposer()) +func toStdTxResponse(cliCtx client.Context, w http.ResponseWriter, data wasmProposalData) { + msg, err := govtypes.NewMsgSubmitProposal(data.Content(), data.GetDeposit(), data.GetProposer()) + if err != nil { + rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) + return + } if err := msg.ValidateBasic(); err != nil { rest.WriteErrorResponse(w, http.StatusBadRequest, err.Error()) return @@ -266,5 +272,5 @@ func toStdTxResponse(cliCtx context.CLIContext, w http.ResponseWriter, data wasm if !baseReq.ValidateBasic(w) { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, baseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, baseReq, msg) } diff --git a/x/wasm/client/rest/new_tx.go b/x/wasm/client/rest/new_tx.go index a4a74676b9..aa10ef199e 100644 --- a/x/wasm/client/rest/new_tx.go +++ b/x/wasm/client/rest/new_tx.go @@ -4,14 +4,14 @@ import ( "net/http" "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" "github.com/gorilla/mux" ) -func registerNewTxRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerNewTxRoutes(cliCtx client.Context, r *mux.Router) { r.HandleFunc("/wasm/contract/{contractAddr}/admin", setContractAdminHandlerFn(cliCtx)).Methods("PUT") r.HandleFunc("/wasm/contract/{contractAddr}/code", migrateContractHandlerFn(cliCtx)).Methods("PUT") } @@ -27,10 +27,10 @@ type updateContractAdministrateReq struct { Admin sdk.AccAddress `json:"admin,omitempty" yaml:"admin"` } -func setContractAdminHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func setContractAdminHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req updateContractAdministrateReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } vars := mux.Vars(r) @@ -47,7 +47,7 @@ func setContractAdminHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - msg := types.MsgUpdateAdmin{ + msg := &types.MsgUpdateAdmin{ Sender: cliCtx.GetFromAddress(), NewAdmin: req.Admin, Contract: contractAddress, @@ -57,14 +57,14 @@ func setContractAdminHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } -func migrateContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func migrateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req migrateContractReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } vars := mux.Vars(r) @@ -81,7 +81,7 @@ func migrateContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - msg := types.MsgMigrateContract{ + msg := &types.MsgMigrateContract{ Sender: cliCtx.GetFromAddress(), Contract: contractAddress, CodeID: req.CodeID, @@ -92,6 +92,6 @@ func migrateContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, msg) } } diff --git a/x/wasm/client/rest/query.go b/x/wasm/client/rest/query.go index 34d8a0a84b..7fc1741078 100644 --- a/x/wasm/client/rest/query.go +++ b/x/wasm/client/rest/query.go @@ -10,14 +10,13 @@ import ( "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - - "github.com/cosmos/cosmos-sdk/client/context" "github.com/gorilla/mux" ) -func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerQueryRoutes(cliCtx client.Context, r *mux.Router) { r.HandleFunc("/wasm/code", listCodesHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/wasm/code/{codeID}", queryCodeHandlerFn(cliCtx)).Methods("GET") r.HandleFunc("/wasm/code/{codeID}/contracts", listContractsByCodeHandlerFn(cliCtx)).Methods("GET") @@ -28,7 +27,7 @@ func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router) { r.HandleFunc("/wasm/contract/{contractAddr}/raw/{key}", queryContractStateRawHandlerFn(cliCtx)).Queries("encoding", "{encoding}").Methods("GET") } -func listCodesHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func listCodesHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { cliCtx, ok := rest.ParseQueryHeightOrReturnBadRequest(w, cliCtx, r) if !ok { @@ -46,7 +45,7 @@ func listCodesHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func queryCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { codeID, err := strconv.ParseUint(mux.Vars(r)["codeID"], 10, 64) if err != nil { @@ -75,7 +74,7 @@ func queryCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func listContractsByCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func listContractsByCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { codeID, err := strconv.ParseUint(mux.Vars(r)["codeID"], 10, 64) if err != nil { @@ -99,7 +98,7 @@ func listContractsByCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func queryContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { @@ -123,7 +122,7 @@ func queryContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { } } -func queryContractStateAllHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryContractStateAllHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { @@ -154,7 +153,8 @@ func queryContractStateAllHandlerFn(cliCtx context.CLIContext) http.HandlerFunc rest.PostProcessResponse(w, cliCtx, resultData) } } -func queryContractStateRawHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { + +func queryContractStateRawHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { decoder := newArgDecoder(hex.DecodeString) addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) @@ -190,7 +190,7 @@ type smartResponse struct { Smart []byte `json:"smart"` } -func queryContractStateSmartHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryContractStateSmartHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { decoder := newArgDecoder(hex.DecodeString) addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) @@ -224,7 +224,7 @@ func queryContractStateSmartHandlerFn(cliCtx context.CLIContext) http.HandlerFun } } -func queryContractHistoryFn(cliCtx context.CLIContext) http.HandlerFunc { +func queryContractHistoryFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { addr, err := sdk.AccAddressFromBech32(mux.Vars(r)["contractAddr"]) if err != nil { diff --git a/x/wasm/client/rest/rest.go b/x/wasm/client/rest/rest.go index fc47da384d..2e697a6b50 100644 --- a/x/wasm/client/rest/rest.go +++ b/x/wasm/client/rest/rest.go @@ -1,13 +1,12 @@ package rest import ( + "github.com/cosmos/cosmos-sdk/client" "github.com/gorilla/mux" - - "github.com/cosmos/cosmos-sdk/client/context" ) // RegisterRoutes registers staking-related REST handlers to a router -func RegisterRoutes(cliCtx context.CLIContext, r *mux.Router) { +func RegisterRoutes(cliCtx client.Context, r *mux.Router) { registerQueryRoutes(cliCtx, r) registerTxRoutes(cliCtx, r) registerNewTxRoutes(cliCtx, r) diff --git a/x/wasm/client/rest/tx.go b/x/wasm/client/rest/tx.go index 006f9f88ef..4db17367ba 100644 --- a/x/wasm/client/rest/tx.go +++ b/x/wasm/client/rest/tx.go @@ -4,17 +4,16 @@ import ( "net/http" "strconv" - "github.com/cosmos/cosmos-sdk/client/context" + wasmUtils "github.com/CosmWasm/wasmd/x/wasm/client/utils" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/tx" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/rest" - "github.com/cosmos/cosmos-sdk/x/auth/client/utils" "github.com/gorilla/mux" - - wasmUtils "github.com/CosmWasm/wasmd/x/wasm/client/utils" - "github.com/CosmWasm/wasmd/x/wasm/internal/types" ) -func registerTxRoutes(cliCtx context.CLIContext, r *mux.Router) { +func registerTxRoutes(cliCtx client.Context, r *mux.Router) { r.HandleFunc("/wasm/code", storeCodeHandlerFn(cliCtx)).Methods("POST") r.HandleFunc("/wasm/code/{codeId}", instantiateContractHandlerFn(cliCtx)).Methods("POST") r.HandleFunc("/wasm/contract/{contractAddr}", executeContractHandlerFn(cliCtx)).Methods("POST") @@ -41,10 +40,10 @@ type executeContractReq struct { Amount sdk.Coins `json:"coins" yaml:"coins"` } -func storeCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func storeCodeHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req storeCodeReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } @@ -89,14 +88,14 @@ func storeCodeHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) } } -func instantiateContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func instantiateContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req instantiateContractReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } vars := mux.Vars(r) @@ -127,14 +126,14 @@ func instantiateContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) } } -func executeContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { +func executeContractHandlerFn(cliCtx client.Context) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var req executeContractReq - if !rest.ReadRESTReq(w, r, cliCtx.Codec, &req) { + if !rest.ReadRESTReq(w, r, cliCtx.LegacyAmino, &req) { return } vars := mux.Vars(r) @@ -163,6 +162,6 @@ func executeContractHandlerFn(cliCtx context.CLIContext) http.HandlerFunc { return } - utils.WriteGenerateStdTxResponse(w, cliCtx, req.BaseReq, []sdk.Msg{msg}) + tx.WriteGeneratedTxResponse(cliCtx, w, req.BaseReq, &msg) } } diff --git a/x/wasm/genesis_test.go b/x/wasm/genesis_test.go index cec6eb9583..8bd4cc5133 100644 --- a/x/wasm/genesis_test.go +++ b/x/wasm/genesis_test.go @@ -4,25 +4,23 @@ import ( "encoding/json" "testing" - "github.com/stretchr/testify/require" - sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/stretchr/testify/require" ) type contractState struct { } func TestInitGenesis(t *testing.T) { - data, cleanup := setupTest(t) - defer cleanup() + data := setupTest(t) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(data.ctx, data.acctKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(data.ctx, data.acctKeeper, topUp) + creator := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, topUp) - h := data.module.NewHandler() - q := data.module.NewQuerierHandler() + h := data.module.Route().Handler() + q := data.module.LegacyQuerierHandler(nil) t.Log("fail with invalid source url") msg := MsgStoreCode{ @@ -35,7 +33,7 @@ func TestInitGenesis(t *testing.T) { err := msg.ValidateBasic() require.Error(t, err) - _, err = h(data.ctx, msg) + _, err = h(data.ctx, &msg) require.Error(t, err) t.Log("fail with relative source url") @@ -49,7 +47,7 @@ func TestInitGenesis(t *testing.T) { err = msg.ValidateBasic() require.Error(t, err) - _, err = h(data.ctx, msg) + _, err = h(data.ctx, &msg) require.Error(t, err) t.Log("fail with invalid build tag") @@ -63,7 +61,7 @@ func TestInitGenesis(t *testing.T) { err = msg.ValidateBasic() require.Error(t, err) - _, err = h(data.ctx, msg) + _, err = h(data.ctx, &msg) require.Error(t, err) t.Log("no error with valid source and build tag") @@ -76,7 +74,7 @@ func TestInitGenesis(t *testing.T) { err = msg.ValidateBasic() require.NoError(t, err) - res, err := h(data.ctx, msg) + res, err := h(data.ctx, &msg) require.NoError(t, err) require.Equal(t, res.Data, []byte("1")) @@ -94,7 +92,7 @@ func TestInitGenesis(t *testing.T) { InitMsg: initMsgBz, InitFunds: deposit, } - res, err = h(data.ctx, initCmd) + res, err = h(data.ctx, &initCmd) require.NoError(t, err) contractAddr := sdk.AccAddress(res.Data) @@ -104,7 +102,7 @@ func TestInitGenesis(t *testing.T) { Msg: []byte(`{"release":{}}`), SentFunds: topUp, } - res, err = h(data.ctx, execCmd) + res, err = h(data.ctx, &execCmd) require.NoError(t, err) // ensure all contract state is as after init @@ -123,12 +121,11 @@ func TestInitGenesis(t *testing.T) { genState := ExportGenesis(data.ctx, data.keeper) // create new app to import genstate into - newData, newCleanup := setupTest(t) - defer newCleanup() - q2 := newData.module.NewQuerierHandler() + newData := setupTest(t) + q2 := newData.module.LegacyQuerierHandler(nil) // initialize new app with genstate - InitGenesis(newData.ctx, newData.keeper, genState) + InitGenesis(newData.ctx, newData.keeper, *genState) // run same checks again on newdata, to make sure it was reinitialized correctly assertCodeList(t, q2, newData.ctx, 1) diff --git a/x/wasm/handler.go b/x/wasm/handler.go index cc7b0d7b90..f04769119f 100644 --- a/x/wasm/handler.go +++ b/x/wasm/handler.go @@ -6,6 +6,7 @@ import ( "github.com/CosmWasm/wasmd/x/wasm/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + abci "github.com/tendermint/tendermint/abci/types" ) // NewHandler returns a handler for "bank" type messages. @@ -14,18 +15,18 @@ func NewHandler(k Keeper) sdk.Handler { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - case MsgStoreCode: - return handleStoreCode(ctx, k, &msg) - case MsgInstantiateContract: - return handleInstantiate(ctx, k, &msg) - case MsgExecuteContract: - return handleExecute(ctx, k, &msg) - case MsgMigrateContract: - return handleMigration(ctx, k, &msg) - case MsgUpdateAdmin: - return handleUpdateContractAdmin(ctx, k, &msg) - case MsgClearAdmin: - return handleClearContractAdmin(ctx, k, &msg) + case *MsgStoreCode: + return handleStoreCode(ctx, k, msg) + case *MsgInstantiateContract: + return handleInstantiate(ctx, k, msg) + case *MsgExecuteContract: + return handleExecute(ctx, k, msg) + case *MsgMigrateContract: + return handleMigration(ctx, k, msg) + case *MsgUpdateAdmin: + return handleUpdateContractAdmin(ctx, k, msg) + case *MsgClearAdmin: + return handleClearContractAdmin(ctx, k, msg) default: errMsg := fmt.Sprintf("unrecognized wasm message type: %T", msg) return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, errMsg) @@ -35,9 +36,9 @@ func NewHandler(k Keeper) sdk.Handler { // filterMessageEvents returns the same events with all of type == EventTypeMessage removed. // this is so only our top-level message event comes through -func filterMessageEvents(manager *sdk.EventManager) sdk.Events { - events := manager.Events() - res := make([]sdk.Event, 0, len(events)+1) +func filteredMessageEvents(manager *sdk.EventManager) []abci.Event { + events := manager.ABCIEvents() + res := make([]abci.Event, 0, len(events)) for _, e := range events { if e.Type != sdk.EventTypeMessage { res = append(res, e) @@ -57,17 +58,18 @@ func handleStoreCode(ctx sdk.Context, k Keeper, msg *MsgStoreCode) (*sdk.Result, return nil, err } - events := filterMessageEvents(ctx.EventManager()) - ourEvent := sdk.NewEvent( - sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName), - sdk.NewAttribute(types.AttributeKeySigner, msg.Sender.String()), - sdk.NewAttribute(types.AttributeKeyCodeID, fmt.Sprintf("%d", codeID)), - ) + ctx.EventManager().EmitEvents(sdk.Events{ + sdk.NewEvent( + sdk.EventTypeMessage, + sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName), + sdk.NewAttribute(types.AttributeKeySigner, msg.Sender.String()), + sdk.NewAttribute(types.AttributeKeyCodeID, fmt.Sprintf("%d", codeID)), + ), + }) return &sdk.Result{ Data: []byte(fmt.Sprintf("%d", codeID)), - Events: append(events, ourEvent), + Events: ctx.EventManager().ABCIEvents(), }, nil } @@ -77,18 +79,19 @@ func handleInstantiate(ctx sdk.Context, k Keeper, msg *MsgInstantiateContract) ( return nil, err } - events := filterMessageEvents(ctx.EventManager()) - ourEvent := sdk.NewEvent( + events := filteredMessageEvents(ctx.EventManager()) + custom := sdk.Events{sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName), sdk.NewAttribute(types.AttributeKeySigner, msg.Sender.String()), sdk.NewAttribute(types.AttributeKeyCodeID, fmt.Sprintf("%d", msg.CodeID)), sdk.NewAttribute(types.AttributeKeyContract, contractAddr.String()), - ) + )} + events = append(events, custom.ToABCIEvents()...) return &sdk.Result{ Data: contractAddr, - Events: append(events, ourEvent), + Events: events, }, nil } @@ -98,15 +101,17 @@ func handleExecute(ctx sdk.Context, k Keeper, msg *MsgExecuteContract) (*sdk.Res return nil, err } - events := filterMessageEvents(ctx.EventManager()) - ourEvent := sdk.NewEvent( + events := filteredMessageEvents(ctx.EventManager()) + custom := sdk.Events{sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName), sdk.NewAttribute(types.AttributeKeySigner, msg.Sender.String()), sdk.NewAttribute(types.AttributeKeyContract, msg.Contract.String()), - ) + ), + } + events = append(events, custom.ToABCIEvents()...) - res.Events = append(events, ourEvent) + res.Events = events return res, nil } @@ -116,14 +121,15 @@ func handleMigration(ctx sdk.Context, k Keeper, msg *MsgMigrateContract) (*sdk.R return nil, err } - events := filterMessageEvents(ctx.EventManager()) - ourEvent := sdk.NewEvent( + events := filteredMessageEvents(ctx.EventManager()) + custom := sdk.Events{sdk.NewEvent( sdk.EventTypeMessage, sdk.NewAttribute(sdk.AttributeKeyModule, ModuleName), sdk.NewAttribute(types.AttributeKeySigner, msg.Sender.String()), sdk.NewAttribute(types.AttributeKeyContract, msg.Contract.String()), - ) - res.Events = append(events, ourEvent) + )} + events = append(events, custom.ToABCIEvents()...) + res.Events = events return res, nil } @@ -139,7 +145,7 @@ func handleUpdateContractAdmin(ctx sdk.Context, k Keeper, msg *MsgUpdateAdmin) ( sdk.NewAttribute(types.AttributeKeyContract, msg.Contract.String()), ) return &sdk.Result{ - Events: append(events, ourEvent), + Events: append(events, ourEvent).ToABCIEvents(), }, nil } @@ -155,6 +161,6 @@ func handleClearContractAdmin(ctx sdk.Context, k Keeper, msg *MsgClearAdmin) (*s sdk.NewAttribute(types.AttributeKeyContract, msg.Contract.String()), ) return &sdk.Result{ - Events: append(events, ourEvent), + Events: append(events, ourEvent).ToABCIEvents(), }, nil } diff --git a/x/wasm/internal/keeper/genesis.go b/x/wasm/internal/keeper/genesis.go index 3a471fb53b..021af53809 100644 --- a/x/wasm/internal/keeper/genesis.go +++ b/x/wasm/internal/keeper/genesis.go @@ -14,7 +14,7 @@ import ( func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) error { var maxCodeID uint64 for i, code := range data.Codes { - err := keeper.importCode(ctx, code.CodeID, code.CodeInfo, code.CodesBytes) + err := keeper.importCode(ctx, code.CodeID, code.CodeInfo, code.CodeBytes) if err != nil { return sdkerrors.Wrapf(err, "code %d with id: %d", i, code.CodeID) } @@ -52,7 +52,7 @@ func InitGenesis(ctx sdk.Context, keeper Keeper, data types.GenesisState) error } // ExportGenesis returns a GenesisState for a given context and keeper. -func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { +func ExportGenesis(ctx sdk.Context, keeper Keeper) *types.GenesisState { var genState types.GenesisState genState.Params = keeper.GetParams(ctx) @@ -63,9 +63,9 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { panic(err) } genState.Codes = append(genState.Codes, types.Code{ - CodeID: codeID, - CodeInfo: info, - CodesBytes: bytecode, + CodeID: codeID, + CodeInfo: info, + CodeBytes: bytecode, }) return false }) @@ -99,5 +99,5 @@ func ExportGenesis(ctx sdk.Context, keeper Keeper) types.GenesisState { }) } - return genState + return &genState } diff --git a/x/wasm/internal/keeper/genesis_test.go b/x/wasm/internal/keeper/genesis_test.go index 0ac40140cc..20f01f9faa 100644 --- a/x/wasm/internal/keeper/genesis_test.go +++ b/x/wasm/internal/keeper/genesis_test.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "encoding/json" "fmt" - "github.com/cosmos/cosmos-sdk/x/distribution" "io/ioutil" "math/rand" "os" @@ -17,14 +16,16 @@ import ( wasmTypes "github.com/CosmWasm/wasmd/x/wasm/internal/types" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/params" - "github.com/cosmos/cosmos-sdk/x/staking" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" fuzz "github.com/google/gofuzz" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" dbm "github.com/tendermint/tm-db" ) @@ -126,9 +127,9 @@ func TestFailFastImport(t *testing.T) { "happy path: code info correct": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Sequences: []types.Sequence{ {IDKey: types.KeyLastCodeID, Value: 2}, @@ -141,13 +142,13 @@ func TestFailFastImport(t *testing.T) { "happy path: code ids can contain gaps": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }, { - CodeID: 3, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: 3, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Sequences: []types.Sequence{ {IDKey: types.KeyLastCodeID, Value: 10}, @@ -160,13 +161,13 @@ func TestFailFastImport(t *testing.T) { "happy path: code order does not matter": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: 2, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }, { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: nil, Sequences: []types.Sequence{ @@ -179,23 +180,23 @@ func TestFailFastImport(t *testing.T) { }, "prevent code hash mismatch": {src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: wasmTypes.CodeInfoFixture(func(i *wasmTypes.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: wasmTypes.CodeInfoFixture(func(i *wasmTypes.CodeInfo) { i.CodeHash = make([]byte, sha256.Size) }), + CodeBytes: wasmCode, }}, Params: types.DefaultParams(), }}, "prevent duplicate codeIDs": {src: types.GenesisState{ Codes: []types.Code{ { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }, { - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }, }, Params: types.DefaultParams(), @@ -203,9 +204,9 @@ func TestFailFastImport(t *testing.T) { "happy path: code id in info and contract do match": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: []types.Contract{ { @@ -224,9 +225,9 @@ func TestFailFastImport(t *testing.T) { "happy path: code info with two contracts": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: []types.Contract{ { @@ -259,9 +260,9 @@ func TestFailFastImport(t *testing.T) { "prevent duplicate contract address": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: []types.Contract{ { @@ -278,9 +279,9 @@ func TestFailFastImport(t *testing.T) { "prevent duplicate contract model keys": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: []types.Contract{ { @@ -313,9 +314,9 @@ func TestFailFastImport(t *testing.T) { "prevent code id seq init value == max codeID used": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: 2, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: 2, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Sequences: []types.Sequence{ {IDKey: types.KeyLastCodeID, Value: 1}, @@ -326,9 +327,9 @@ func TestFailFastImport(t *testing.T) { "prevent contract id seq init value == count contracts": { src: types.GenesisState{ Codes: []types.Code{{ - CodeID: firstCodeID, - CodeInfo: myCodeInfo, - CodesBytes: wasmCode, + CodeID: firstCodeID, + CodeInfo: myCodeInfo, + CodeBytes: wasmCode, }}, Contracts: []types.Contract{ { @@ -362,7 +363,7 @@ func TestFailFastImport(t *testing.T) { } func TestImportContractWithCodeHistoryReset(t *testing.T) { - genesis := ` + genesisTemplate := ` { "params":{ "code_upload_access": { @@ -410,14 +411,14 @@ 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")...))) + var importState wasmTypes.GenesisState - err = keeper.cdc.UnmarshalJSON([]byte( - fmt.Sprintf(genesis, enc64(wasmCodeHash[:]), enc64(wasmCode), - enc64(append([]byte{0x04}, []byte("lastCodeId")...)), - enc64(append([]byte{0x04}, []byte("lastContractId")...))), - ), &importState) + err = keeper.cdc.UnmarshalJSON([]byte(genesisStr), &importState) require.NoError(t, err) - require.NoError(t, importState.ValidateBasic()) + require.NoError(t, importState.ValidateBasic(), genesisStr) ctx = ctx.WithBlockHeight(0).WithGasMeter(sdk.NewInfiniteGasMeter()) @@ -440,8 +441,8 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) { Source: "https://example.com", Builder: "foo/bar:tag", InstantiateConfig: wasmTypes.AccessConfig{ - Type: types.OnlyAddress, - Address: codeCreatorAddr, + Permission: types.AccessTypeOnlyAddress, + Address: codeCreatorAddr, }, } assert.Equal(t, expCodeInfo, *gotCodeInfo) @@ -463,12 +464,12 @@ func TestImportContractWithCodeHistoryReset(t *testing.T) { assert.Equal(t, expContractInfo, *gotContractInfo) expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.GenesisContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeGenesis, CodeID: firstCodeID, Updated: types.NewAbsoluteTxPosition(ctx), }, } - assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr).CodeHistoryEntries) } func setupKeeper(t *testing.T) (Keeper, sdk.Context, []sdk.StoreKey, func()) { @@ -478,8 +479,8 @@ func setupKeeper(t *testing.T) (Keeper, sdk.Context, []sdk.StoreKey, func()) { cleanup := func() { os.RemoveAll(tempDir) } //t.Cleanup(cleanup) todo: add with Go 1.14 var ( - keyParams = sdk.NewKVStoreKey(params.StoreKey) - tkeyParams = sdk.NewTransientStoreKey(params.TStoreKey) + keyParams = sdk.NewKVStoreKey(paramtypes.StoreKey) + tkeyParams = sdk.NewTransientStoreKey(paramtypes.TStoreKey) keyWasm = sdk.NewKVStoreKey(wasmTypes.StoreKey) ) @@ -490,14 +491,16 @@ func setupKeeper(t *testing.T) (Keeper, sdk.Context, []sdk.StoreKey, func()) { ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) require.NoError(t, ms.LoadLatestVersion()) - ctx := sdk.NewContext(ms, abci.Header{ + ctx := sdk.NewContext(ms, tmproto.Header{ Height: 1234567, Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), }, false, log.NewNopLogger()) - cdc := MakeTestCodec() - pk := params.NewKeeper(cdc, keyParams, tkeyParams) + + encodingConfig := MakeEncodingConfig() wasmConfig := wasmTypes.DefaultWasmConfig() - srcKeeper := NewKeeper(cdc, keyWasm, pk.Subspace(wasmTypes.DefaultParamspace), auth.AccountKeeper{}, nil, staking.Keeper{}, distribution.Keeper{}, nil, tempDir, wasmConfig, "", nil, nil) + 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, tempDir, wasmConfig, "", nil, nil) srcKeeper.setParams(ctx, wasmTypes.DefaultParams()) return srcKeeper, ctx, []sdk.StoreKey{keyWasm, keyParams}, cleanup diff --git a/x/wasm/internal/keeper/handler_plugin.go b/x/wasm/internal/keeper/handler_plugin.go index a8be89b4a7..f9ad03022f 100644 --- a/x/wasm/internal/keeper/handler_plugin.go +++ b/x/wasm/internal/keeper/handler_plugin.go @@ -8,9 +8,9 @@ import ( "github.com/CosmWasm/wasmd/x/wasm/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/staking" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) type MessageHandler struct { @@ -87,24 +87,16 @@ func EncodeBankMsg(sender sdk.AccAddress, msg *wasmTypes.BankMsg) ([]sdk.Msg, er if len(msg.Send.Amount) == 0 { return nil, nil } - fromAddr, stderr := sdk.AccAddressFromBech32(msg.Send.FromAddress) - if stderr != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Send.FromAddress) - } - toAddr, stderr := sdk.AccAddressFromBech32(msg.Send.ToAddress) - if stderr != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Send.ToAddress) - } toSend, err := convertWasmCoinsToSdkCoins(msg.Send.Amount) if err != nil { return nil, err } - sdkMsg := bank.MsgSend{ - FromAddress: fromAddr, - ToAddress: toAddr, + sdkMsg := banktypes.MsgSend{ + FromAddress: msg.Send.FromAddress, + ToAddress: msg.Send.ToAddress, Amount: toSend, } - return []sdk.Msg{sdkMsg}, nil + return []sdk.Msg{&sdkMsg}, nil } func NoCustomMsg(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { @@ -112,87 +104,65 @@ func NoCustomMsg(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) } func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmTypes.StakingMsg) ([]sdk.Msg, error) { - if msg.Delegate != nil { - validator, err := sdk.ValAddressFromBech32(msg.Delegate.Validator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Delegate.Validator) - } + switch { + case msg.Delegate != nil: coin, err := convertWasmCoinToSdkCoin(msg.Delegate.Amount) if err != nil { return nil, err } - sdkMsg := staking.MsgDelegate{ - DelegatorAddress: sender, - ValidatorAddress: validator, + sdkMsg := stakingtypes.MsgDelegate{ + DelegatorAddress: sender.String(), + ValidatorAddress: msg.Delegate.Validator, Amount: coin, } - return []sdk.Msg{sdkMsg}, nil - } - if msg.Redelegate != nil { - src, err := sdk.ValAddressFromBech32(msg.Redelegate.SrcValidator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Redelegate.SrcValidator) - } - dst, err := sdk.ValAddressFromBech32(msg.Redelegate.DstValidator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Redelegate.DstValidator) - } + return []sdk.Msg{&sdkMsg}, nil + + case msg.Redelegate != nil: coin, err := convertWasmCoinToSdkCoin(msg.Redelegate.Amount) if err != nil { return nil, err } - sdkMsg := staking.MsgBeginRedelegate{ - DelegatorAddress: sender, - ValidatorSrcAddress: src, - ValidatorDstAddress: dst, + sdkMsg := stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: sender.String(), + ValidatorSrcAddress: msg.Redelegate.SrcValidator, + ValidatorDstAddress: msg.Redelegate.DstValidator, Amount: coin, } - return []sdk.Msg{sdkMsg}, nil - } - if msg.Undelegate != nil { - validator, err := sdk.ValAddressFromBech32(msg.Undelegate.Validator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Undelegate.Validator) - } + return []sdk.Msg{&sdkMsg}, nil + case msg.Undelegate != nil: coin, err := convertWasmCoinToSdkCoin(msg.Undelegate.Amount) if err != nil { return nil, err } - sdkMsg := staking.MsgUndelegate{ - DelegatorAddress: sender, - ValidatorAddress: validator, + sdkMsg := stakingtypes.MsgUndelegate{ + DelegatorAddress: sender.String(), + ValidatorAddress: msg.Undelegate.Validator, Amount: coin, } - return []sdk.Msg{sdkMsg}, nil - } - if msg.Withdraw != nil { - var err error - rcpt := sender + return []sdk.Msg{&sdkMsg}, nil + case msg.Withdraw != nil: + senderAddr := sender.String() + rcpt := senderAddr if len(msg.Withdraw.Recipient) != 0 { - rcpt, err = sdk.AccAddressFromBech32(msg.Withdraw.Recipient) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Withdraw.Recipient) - } + rcpt = msg.Withdraw.Recipient } - validator, err := sdk.ValAddressFromBech32(msg.Withdraw.Validator) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Withdraw.Validator) - } - setMsg := distribution.MsgSetWithdrawAddress{ - DelegatorAddress: sender, + setMsg := distributiontypes.MsgSetWithdrawAddress{ + DelegatorAddress: senderAddr, WithdrawAddress: rcpt, } - withdrawMsg := distribution.MsgWithdrawDelegatorReward{ - DelegatorAddress: sender, - ValidatorAddress: validator, + withdrawMsg := distributiontypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: senderAddr, + ValidatorAddress: msg.Withdraw.Validator, } - return []sdk.Msg{setMsg, withdrawMsg}, nil + return []sdk.Msg{&setMsg, &withdrawMsg}, nil + default: + return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Staking") } - return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Staking") } func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, error) { - if msg.Execute != nil { + switch { + case msg.Execute != nil: contractAddr, err := sdk.AccAddressFromBech32(msg.Execute.ContractAddr) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, msg.Execute.ContractAddr) @@ -208,9 +178,8 @@ func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, er Msg: msg.Execute.Msg, SentFunds: coins, } - return []sdk.Msg{sdkMsg}, nil - } - if msg.Instantiate != nil { + return []sdk.Msg{&sdkMsg}, nil + case msg.Instantiate != nil: coins, err := convertWasmCoinsToSdkCoins(msg.Instantiate.Send) if err != nil { return nil, err @@ -224,9 +193,10 @@ func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, er InitMsg: msg.Instantiate.Msg, InitFunds: coins, } - return []sdk.Msg{sdkMsg}, nil + return []sdk.Msg{&sdkMsg}, nil + default: + return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Wasm") } - return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Wasm") } func (h MessageHandler) Dispatch(ctx sdk.Context, contractAddr sdk.AccAddress, msg wasmTypes.CosmosMsg) error { @@ -243,6 +213,9 @@ func (h MessageHandler) Dispatch(ctx sdk.Context, contractAddr sdk.AccAddress, m } func (h MessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Address, msg sdk.Msg) error { + if err := msg.ValidateBasic(); err != nil { + return err + } // make sure this account can send it for _, acct := range msg.GetSigners() { if !acct.Equals(contractAddr) { @@ -259,8 +232,13 @@ func (h MessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Addre if err != nil { return err } + + events := make(sdk.Events, len(res.Events)) + for i := range res.Events { + events[i] = sdk.Event(res.Events[i]) + } // redispatch all events, (type sdk.EventTypeMessage will be filtered out in the handler) - ctx.EventManager().EmitEvents(res.Events) + ctx.EventManager().EmitEvents(events) return nil } diff --git a/x/wasm/internal/keeper/handler_plugin_test.go b/x/wasm/internal/keeper/handler_plugin_test.go index 4351430683..5d2883704d 100644 --- a/x/wasm/internal/keeper/handler_plugin_test.go +++ b/x/wasm/internal/keeper/handler_plugin_test.go @@ -3,16 +3,16 @@ package keeper import ( "encoding/json" "fmt" - "github.com/CosmWasm/wasmd/x/wasm/internal/types" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "testing" wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEncoding(t *testing.T) { @@ -55,9 +55,9 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - bank.MsgSend{ - FromAddress: addr1, - ToAddress: addr2, + &banktypes.MsgSend{ + FromAddress: addr1.String(), + ToAddress: addr2.String(), Amount: sdk.Coins{ sdk.NewInt64Coin("uatom", 12345), sdk.NewInt64Coin("usdt", 54321), @@ -99,7 +99,16 @@ func TestEncoding(t *testing.T) { }, }, }, - isError: true, + isError: false, // addresses are checked in the handler + output: []sdk.Msg{ + &banktypes.MsgSend{ + FromAddress: addr1.String(), + ToAddress: invalidAddr, + Amount: sdk.Coins{ + sdk.NewInt64Coin("uatom", 7890), + }, + }, + }, }, "wasm execute": { sender: addr1, @@ -115,7 +124,7 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - types.MsgExecuteContract{ + &types.MsgExecuteContract{ Sender: addr1, Contract: addr2, Msg: jsonMsg, @@ -137,7 +146,7 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - types.MsgInstantiateContract{ + &types.MsgInstantiateContract{ Sender: addr1, CodeID: 7, // TODO: fix this @@ -158,9 +167,9 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - staking.MsgDelegate{ - DelegatorAddress: addr1, - ValidatorAddress: valAddr, + &stakingtypes.MsgDelegate{ + DelegatorAddress: addr1.String(), + ValidatorAddress: valAddr.String(), Amount: sdk.NewInt64Coin("stake", 777), }, }, @@ -175,7 +184,14 @@ func TestEncoding(t *testing.T) { }, }, }, - isError: true, + isError: false, // fails in the handler + output: []sdk.Msg{ + &stakingtypes.MsgDelegate{ + DelegatorAddress: addr1.String(), + ValidatorAddress: addr2.String(), + Amount: sdk.NewInt64Coin("stake", 777), + }, + }, }, "staking undelegate": { sender: addr1, @@ -188,9 +204,9 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - staking.MsgUndelegate{ - DelegatorAddress: addr1, - ValidatorAddress: valAddr, + &stakingtypes.MsgUndelegate{ + DelegatorAddress: addr1.String(), + ValidatorAddress: valAddr.String(), Amount: sdk.NewInt64Coin("stake", 555), }, }, @@ -207,10 +223,10 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - staking.MsgBeginRedelegate{ - DelegatorAddress: addr1, - ValidatorSrcAddress: valAddr, - ValidatorDstAddress: valAddr2, + &stakingtypes.MsgBeginRedelegate{ + DelegatorAddress: addr1.String(), + ValidatorSrcAddress: valAddr.String(), + ValidatorDstAddress: valAddr2.String(), Amount: sdk.NewInt64Coin("stake", 222), }, }, @@ -225,13 +241,13 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - distribution.MsgSetWithdrawAddress{ - DelegatorAddress: addr1, - WithdrawAddress: addr1, + &distributiontypes.MsgSetWithdrawAddress{ + DelegatorAddress: addr1.String(), + WithdrawAddress: addr1.String(), }, - distribution.MsgWithdrawDelegatorReward{ - DelegatorAddress: addr1, - ValidatorAddress: valAddr2, + &distributiontypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: addr1.String(), + ValidatorAddress: valAddr2.String(), }, }, }, @@ -246,13 +262,13 @@ func TestEncoding(t *testing.T) { }, }, output: []sdk.Msg{ - distribution.MsgSetWithdrawAddress{ - DelegatorAddress: addr1, - WithdrawAddress: addr2, + &distributiontypes.MsgSetWithdrawAddress{ + DelegatorAddress: addr1.String(), + WithdrawAddress: addr2.String(), }, - distribution.MsgWithdrawDelegatorReward{ - DelegatorAddress: addr1, - ValidatorAddress: valAddr2, + &distributiontypes.MsgWithdrawDelegatorReward{ + DelegatorAddress: addr1.String(), + ValidatorAddress: valAddr2.String(), }, }, }, diff --git a/x/wasm/internal/keeper/keeper.go b/x/wasm/internal/keeper/keeper.go index 660e7e6a2b..da96f26489 100644 --- a/x/wasm/internal/keeper/keeper.go +++ b/x/wasm/internal/keeper/keeper.go @@ -3,13 +3,8 @@ package keeper import ( "bytes" "encoding/binary" - "github.com/cosmos/cosmos-sdk/x/distribution" "path/filepath" - "github.com/cosmos/cosmos-sdk/x/params/subspace" - "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/pkg/errors" - wasm "github.com/CosmWasm/go-cosmwasm" wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" @@ -17,9 +12,11 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/params" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/tendermint/tendermint/crypto" ) @@ -46,9 +43,9 @@ const CompileCost uint64 = 2 // Keeper will have a reference to Wasmer with it's own data directory. type Keeper struct { storeKey sdk.StoreKey - cdc *codec.Codec - accountKeeper auth.AccountKeeper - bankKeeper bank.Keeper + cdc codec.Marshaler + accountKeeper authkeeper.AccountKeeper + bankKeeper bankkeeper.Keeper wasmer wasm.Wasmer queryPlugins QueryPlugins @@ -56,14 +53,26 @@ type Keeper struct { // queryGasLimit is the max wasm gas that can be spent on executing a query with a contract queryGasLimit uint64 authZPolicy AuthorizationPolicy - paramSpace subspace.Subspace + paramSpace paramtypes.Subspace } // NewKeeper creates a new contract Keeper instance // If customEncoders is non-nil, we can use this to override some of the message handler, especially custom -func NewKeeper(cdc *codec.Codec, storeKey sdk.StoreKey, paramSpace params.Subspace, accountKeeper auth.AccountKeeper, bankKeeper bank.Keeper, - stakingKeeper staking.Keeper, distKeeper distribution.Keeper, - router sdk.Router, homeDir string, wasmConfig types.WasmConfig, supportedFeatures string, customEncoders *MessageEncoders, customPlugins *QueryPlugins) Keeper { +func NewKeeper( + cdc codec.Marshaler, + storeKey sdk.StoreKey, + paramSpace paramtypes.Subspace, + accountKeeper authkeeper.AccountKeeper, + bankKeeper bankkeeper.Keeper, + stakingKeeper stakingkeeper.Keeper, + distKeeper distributionkeeper.Keeper, + router sdk.Router, + homeDir string, + wasmConfig types.WasmConfig, + supportedFeatures string, + customEncoders *MessageEncoders, + customPlugins *QueryPlugins, +) Keeper { wasmer, err := wasm.NewWasmer(filepath.Join(homeDir, "wasm"), supportedFeatures) if err != nil { panic(err) @@ -140,7 +149,7 @@ func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte, } codeInfo := types.NewCodeInfo(codeHash, creator, source, builder, *instantiateAccess) // 0x01 | codeID (uint64) -> ContractInfo - store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshalBinaryBare(codeInfo)) + store.Set(types.GetCodeKey(codeID), k.cdc.MustMarshalBinaryBare(&codeInfo)) return codeID, nil } @@ -164,7 +173,7 @@ func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeIn return sdkerrors.Wrapf(types.ErrDuplicate, "duplicate code: %d", codeID) } // 0x01 | codeID (uint64) -> ContractInfo - store.Set(key, k.cdc.MustMarshalBinaryBare(codeInfo)) + store.Set(key, k.cdc.MustMarshalBinaryBare(&codeInfo)) return nil } @@ -185,7 +194,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // deposit initial contract funds if !deposit.IsZero() { - if k.bankKeeper.BlacklistedAddr(creator) { + if k.bankKeeper.BlockedAddr(creator) { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "blocked address can not be used") } sdkerr := k.bankKeeper.SendCoins(ctx, creator, contractAddress, deposit) @@ -247,7 +256,7 @@ func (k Keeper) instantiate(ctx sdk.Context, codeID uint64, creator, admin sdk.A // persist instance createdAt := types.NewAbsoluteTxPosition(ctx) instance := types.NewContractInfo(codeID, creator, admin, label, createdAt) - store.Set(types.GetContractAddressKey(contractAddress), k.cdc.MustMarshalBinaryBare(instance)) + store.Set(types.GetContractAddressKey(contractAddress), k.cdc.MustMarshalBinaryBare(&instance)) k.appendToContractHistory(ctx, contractAddress, instance.InitialHistory(initMsg)) return contractAddress, nil } @@ -263,7 +272,7 @@ func (k Keeper) Execute(ctx sdk.Context, contractAddress sdk.AccAddress, caller // add more funds if !coins.IsZero() { - if k.bankKeeper.BlacklistedAddr(caller) { + if k.bankKeeper.BlockedAddr(caller) { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "blocked address can not be used") } @@ -343,7 +352,7 @@ func (k Keeper) migrate(ctx sdk.Context, contractAddress sdk.AccAddress, caller return nil, sdkerrors.Wrap(types.ErrMigrationFailed, err.Error()) } - // emit all events from this contract itself + // emit all events from this contract migration itself events := types.ParseEvents(res.Attributes, contractAddress) ctx.EventManager().EmitEvents(events) @@ -384,19 +393,20 @@ func (k Keeper) setContractAdmin(ctx sdk.Context, contractAddress, caller, newAd } func (k Keeper) appendToContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress, newEntries ...types.ContractCodeHistoryEntry) { - entries := append(k.GetContractHistory(ctx, contractAddr), newEntries...) + history := k.GetContractHistory(ctx, contractAddr) + history.CodeHistoryEntries = append(history.CodeHistoryEntries, newEntries...) prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ContractHistoryStorePrefix) - prefixStore.Set(contractAddr, k.cdc.MustMarshalBinaryBare(&entries)) + prefixStore.Set(contractAddr, k.cdc.MustMarshalBinaryBare(&history)) } -func (k Keeper) GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) []types.ContractCodeHistoryEntry { +func (k Keeper) GetContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress) types.ContractHistory { prefixStore := prefix.NewStore(ctx.KVStore(k.storeKey), types.ContractHistoryStorePrefix) - var entries []types.ContractCodeHistoryEntry bz := prefixStore.Get(contractAddr) - if bz != nil { - k.cdc.MustUnmarshalBinaryBare(bz, &entries) + var history types.ContractHistory + if len(bz) != 0 { + k.cdc.MustUnmarshalBinaryBare(bz, &history) } - return entries + return history } // QuerySmart queries the smart contract itself. @@ -637,10 +647,10 @@ func (k Keeper) importAutoIncrementID(ctx sdk.Context, lastIDKey []byte, val uin func (k Keeper) importContract(ctx sdk.Context, contractAddr sdk.AccAddress, c *types.ContractInfo, state []types.Model) error { if !k.containsCodeInfo(ctx, c.CodeID) { - return errors.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) + return sdkerrors.Wrapf(types.ErrNotFound, "code id: %d", c.CodeID) } if k.containsContractInfo(ctx, contractAddr) { - return errors.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) + return sdkerrors.Wrapf(types.ErrDuplicate, "contract: %s", contractAddr) } historyEntry := c.ResetFromGenesis(ctx) diff --git a/x/wasm/internal/keeper/keeper_test.go b/x/wasm/internal/keeper/keeper_test.go index 1a545668c4..1a62982184 100644 --- a/x/wasm/internal/keeper/keeper_test.go +++ b/x/wasm/internal/keeper/keeper_test.go @@ -2,11 +2,9 @@ package keeper import ( "bytes" - "encoding/binary" "encoding/json" "errors" "io/ioutil" - "os" "testing" "time" @@ -14,34 +12,25 @@ import ( stypes "github.com/cosmos/cosmos-sdk/store/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/supply" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/crypto" - "github.com/tendermint/tendermint/crypto/ed25519" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" ) const SupportedFeatures = "staking" func TestNewKeeper(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - _, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) + _, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) require.NotNil(t, keepers.WasmKeeper) } func TestCreate(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -68,35 +57,31 @@ func TestCreateStoresInstantiatePermission(t *testing.T) { expInstConf types.AccessConfig }{ "default": { - srcPermission: types.DefaultParams().DefaultInstantiatePermission, + srcPermission: types.DefaultParams().InstantiateDefaultPermission, expInstConf: types.AllowEverybody, }, "everybody": { - srcPermission: types.Everybody, + srcPermission: types.AccessTypeEverybody, expInstConf: types.AllowEverybody, }, "nobody": { - srcPermission: types.Nobody, + srcPermission: types.AccessTypeNobody, expInstConf: types.AllowNobody, }, "onlyAddress with matching address": { - srcPermission: types.OnlyAddress, - expInstConf: types.AccessConfig{Type: types.OnlyAddress, Address: myAddr}, + srcPermission: types.AccessTypeOnlyAddress, + expInstConf: types.AccessConfig{Permission: types.AccessTypeOnlyAddress, Address: myAddr}, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper keeper.setParams(ctx, types.Params{ - UploadAccess: types.AllowEverybody, - DefaultInstantiatePermission: spec.srcPermission, + CodeUploadAccess: types.AllowEverybody, + InstantiateDefaultPermission: spec.srcPermission, }) - fundAccounts(ctx, accKeeper, myAddr, deposit) + fundAccounts(t, ctx, accKeeper, bankKeeper, myAddr, deposit) codeID, err := keeper.Create(ctx, myAddr, wasmCode, "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", "any/builder:tag", nil) require.NoError(t, err) @@ -109,15 +94,12 @@ func TestCreateStoresInstantiatePermission(t *testing.T) { } func TestCreateWithParamPermissions(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.WasmKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) - otherAddr := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) + otherAddr := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -137,17 +119,17 @@ func TestCreateWithParamPermissions(t *testing.T) { expError: sdkerrors.ErrUnauthorized, }, "onlyAddress with matching address": { - srcPermission: types.OnlyAddress.With(creator), + srcPermission: types.AccessTypeOnlyAddress.With(creator), }, "onlyAddress with non matching address": { - srcPermission: types.OnlyAddress.With(otherAddr), + srcPermission: types.AccessTypeOnlyAddress.With(otherAddr), expError: sdkerrors.ErrUnauthorized, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { params := types.DefaultParams() - params.UploadAccess = spec.srcPermission + params.CodeUploadAccess = spec.srcPermission keeper.setParams(ctx, params) _, err := keeper.Create(ctx, creator, wasmCode, "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", "any/builder:tag", nil) require.True(t, spec.expError.Is(err), err) @@ -159,14 +141,11 @@ func TestCreateWithParamPermissions(t *testing.T) { } func TestCreateDuplicate(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -191,17 +170,14 @@ func TestCreateDuplicate(t *testing.T) { } func TestCreateWithSimulation(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper - ctx = ctx.WithBlockHeader(abci.Header{Height: 1}). + ctx = ctx.WithBlockHeader(tmproto.Header{Height: 1}). WithGasMeter(stypes.NewInfiniteGasMeter()) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -212,7 +188,7 @@ func TestCreateWithSimulation(t *testing.T) { require.Equal(t, uint64(1), contractID) // then try to create it in non-simulation mode (should not fail) - ctx, keepers = CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) + ctx, keepers = CreateTestInput(t, false, SupportedFeatures, nil, nil) accKeeper, keeper = keepers.AccountKeeper, keepers.WasmKeeper contractID, err = keeper.Create(ctx, creator, wasmCode, "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", "any/builder:tag", nil) require.NoError(t, err) @@ -230,15 +206,15 @@ func TestIsSimulationMode(t *testing.T) { exp bool }{ "genesis block": { - ctx: sdk.Context{}.WithBlockHeader(abci.Header{}).WithGasMeter(stypes.NewInfiniteGasMeter()), + ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{}).WithGasMeter(stypes.NewInfiniteGasMeter()), exp: false, }, "any regular block": { - ctx: sdk.Context{}.WithBlockHeader(abci.Header{Height: 1}).WithGasMeter(stypes.NewGasMeter(10000000)), + ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewGasMeter(10000000)), exp: false, }, "simulation": { - ctx: sdk.Context{}.WithBlockHeader(abci.Header{Height: 1}).WithGasMeter(stypes.NewInfiniteGasMeter()), + ctx: sdk.Context{}.WithBlockHeader(tmproto.Header{Height: 1}).WithGasMeter(stypes.NewInfiniteGasMeter()), exp: true, }, } @@ -250,14 +226,11 @@ func TestIsSimulationMode(t *testing.T) { } func TestCreateWithGzippedPayload(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm.gzip") require.NoError(t, err) @@ -274,14 +247,11 @@ func TestCreateWithGzippedPayload(t *testing.T) { } func TestInstantiate(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -292,7 +262,7 @@ func TestInstantiate(t *testing.T) { _, _, bob := keyPubAddr() _, _, fred := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, } @@ -307,7 +277,7 @@ func TestInstantiate(t *testing.T) { require.Equal(t, "cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5", contractAddr.String()) gasAfter := ctx.GasMeter().GasConsumed() - require.Equal(t, uint64(0x10c50), gasAfter-gasBefore) + require.Equal(t, uint64(0x112ad), gasAfter-gasBefore) // ensure it is stored properly info := keeper.GetContractInfo(ctx, contractAddr) @@ -317,12 +287,12 @@ func TestInstantiate(t *testing.T) { assert.Equal(t, info.Label, "demo contract 1") exp := []types.ContractCodeHistoryEntry{{ - Operation: types.InitContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeInit, CodeID: codeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: json.RawMessage(initMsgBz), }} - assert.Equal(t, exp, keeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, exp, keeper.GetContractHistory(ctx, contractAddr).CodeHistoryEntries) } func TestInstantiateWithDeposit(t *testing.T) { @@ -334,7 +304,7 @@ func TestInstantiateWithDeposit(t *testing.T) { fred = bytes.Repeat([]byte{2}, sdk.AddrLen) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) - initMsg = InitMsg{Verifier: fred, Beneficiary: bob} + initMsg = HackatomExampleInitMsg{Verifier: fred, Beneficiary: bob} ) initMsgBz, err := json.Marshal(initMsg) @@ -354,21 +324,18 @@ func TestInstantiateWithDeposit(t *testing.T) { expError: true, }, "blocked address": { - srcActor: supply.NewModuleAddress(auth.FeeCollectorName), + srcActor: authtypes.NewModuleAddress(authtypes.FeeCollectorName), fundAddr: true, expError: true, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.WasmKeeper if spec.fundAddr { - fundAccounts(ctx, accKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) + fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) } contractID, err := keeper.Create(ctx, spec.srcActor, wasmCode, "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", "", nil) require.NoError(t, err) @@ -381,8 +348,8 @@ func TestInstantiateWithDeposit(t *testing.T) { return } require.NoError(t, err) - contractAccount := accKeeper.GetAccount(ctx, addr) - assert.Equal(t, deposit, contractAccount.GetCoins()) + balances := bankKeeper.GetAllBalances(ctx, addr) + assert.Equal(t, deposit, balances) }) } } @@ -398,7 +365,7 @@ func TestInstantiateWithPermissions(t *testing.T) { anyAddr = bytes.Repeat([]byte{3}, sdk.AddrLen) ) - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: anyAddr, Beneficiary: anyAddr, } @@ -424,23 +391,19 @@ func TestInstantiateWithPermissions(t *testing.T) { expError: sdkerrors.ErrUnauthorized, }, "onlyAddress with matching address": { - srcPermission: types.OnlyAddress.With(myAddr), + srcPermission: types.AccessTypeOnlyAddress.With(myAddr), srcActor: myAddr, }, "onlyAddress with non matching address": { - srcPermission: types.OnlyAddress.With(otherAddr), + srcPermission: types.AccessTypeOnlyAddress.With(otherAddr), expError: sdkerrors.ErrUnauthorized, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper - fundAccounts(ctx, accKeeper, spec.srcActor, deposit) + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.WasmKeeper + fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, deposit) contractID, err := keeper.Create(ctx, myAddr, wasmCode, "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", "", &spec.srcPermission) require.NoError(t, err) @@ -452,18 +415,13 @@ func TestInstantiateWithPermissions(t *testing.T) { } func TestInstantiateWithNonExistingCodeID(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) - require.NoError(t, err) - - initMsg := InitMsg{} + initMsg := HackatomExampleInitMsg{} initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) @@ -474,16 +432,13 @@ func TestInstantiateWithNonExistingCodeID(t *testing.T) { } func TestExecute(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -492,7 +447,7 @@ func TestExecute(t *testing.T) { require.NoError(t, err) _, _, bob := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, } @@ -511,19 +466,19 @@ func TestExecute(t *testing.T) { creatorAcct := accKeeper.GetAccount(ctx, creator) require.NotNil(t, creatorAcct) // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, creatorAcct.GetCoins()) + assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, creatorAcct.GetAddress())) // ensure contract has updated balance contractAcct := accKeeper.GetAccount(ctx, addr) require.NotNil(t, contractAcct) - assert.Equal(t, deposit, contractAcct.GetCoins()) + assert.Equal(t, deposit, bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) // unauthorized - trialCtx so we don't change state trialCtx := ctx.WithMultiStore(ctx.MultiStore().CacheWrap().(sdk.MultiStore)) res, err := keeper.Execute(trialCtx, addr, creator, []byte(`{"release":{}}`), nil) require.Error(t, err) require.True(t, errors.Is(err, types.ErrExecuteFailed)) - require.Equal(t, err.Error(), "execute wasm contract failed: Unauthorized") + require.Equal(t, "Unauthorized: execute wasm contract failed", err.Error()) // verifier can execute, and get proper gas amount start := time.Now() @@ -536,18 +491,18 @@ func TestExecute(t *testing.T) { // make sure gas is properly deducted from ctx gasAfter := ctx.GasMeter().GasConsumed() - require.Equal(t, uint64(0x11615), gasAfter-gasBefore) + require.Equal(t, uint64(0x11e33), gasAfter-gasBefore) // ensure bob now exists and got both payments released bobAcct = accKeeper.GetAccount(ctx, bob) require.NotNil(t, bobAcct) - balance := bobAcct.GetCoins() + balance := bankKeeper.GetAllBalances(ctx, bobAcct.GetAddress()) assert.Equal(t, deposit.Add(topUp...), balance) // ensure contract has updated balance contractAcct = accKeeper.GetAccount(ctx, addr) require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins(nil), contractAcct.GetCoins()) + assert.Equal(t, sdk.Coins(nil), bankKeeper.GetAllBalances(ctx, contractAcct.GetAddress())) t.Logf("Duration: %v (%d gas)\n", diff, gasAfter-gasBefore) } @@ -559,7 +514,7 @@ func TestExecuteWithDeposit(t *testing.T) { var ( bob = bytes.Repeat([]byte{1}, sdk.AddrLen) fred = bytes.Repeat([]byte{2}, sdk.AddrLen) - blockedAddr = supply.NewModuleAddress(auth.FeeCollectorName) + blockedAddr = authtypes.NewModuleAddress(authtypes.FeeCollectorName) deposit = sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) ) @@ -594,19 +549,16 @@ func TestExecuteWithDeposit(t *testing.T) { } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, bankKeeper, keeper := keepers.AccountKeeper, keepers.BankKeeper, keepers.WasmKeeper if spec.fundAddr { - fundAccounts(ctx, accKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) + fundAccounts(t, ctx, accKeeper, bankKeeper, spec.srcActor, sdk.NewCoins(sdk.NewInt64Coin("denom", 200))) } codeID, err := keeper.Create(ctx, spec.srcActor, wasmCode, "https://example.com/escrow.wasm", "", nil) require.NoError(t, err) - initMsg := InitMsg{Verifier: spec.srcActor, Beneficiary: spec.beneficiary} + initMsg := HackatomExampleInitMsg{Verifier: spec.srcActor, Beneficiary: spec.beneficiary} initMsgBz, err := json.Marshal(initMsg) require.NoError(t, err) @@ -622,39 +574,33 @@ func TestExecuteWithDeposit(t *testing.T) { return } require.NoError(t, err) - beneficiaryAccount := accKeeper.GetAccount(ctx, spec.beneficiary) - assert.Equal(t, deposit, beneficiaryAccount.GetCoins()) + balances := bankKeeper.GetAllBalances(ctx, spec.beneficiary) + assert.Equal(t, deposit, balances) }) } } func TestExecuteWithNonExistingAddress(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) // unauthorized - trialCtx so we don't change state nonExistingAddress := addrFromUint64(9999) - _, err = keeper.Execute(ctx, nonExistingAddress, creator, []byte(`{}`), nil) + _, err := keeper.Execute(ctx, nonExistingAddress, creator, []byte(`{}`), nil) require.True(t, types.ErrNotFound.Is(err), err) } func TestExecuteWithPanic(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -663,7 +609,7 @@ func TestExecuteWithPanic(t *testing.T) { require.NoError(t, err) _, _, bob := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, } @@ -677,20 +623,17 @@ func TestExecuteWithPanic(t *testing.T) { _, err = keeper.Execute(ctx, addr, fred, []byte(`{"panic":{}}`), topUp) require.Error(t, err) require.True(t, errors.Is(err, types.ErrExecuteFailed)) - require.Equal(t, err.Error(), "execute wasm contract failed: Out of gas") + require.Equal(t, "Out of gas: execute wasm contract failed", err.Error()) } func TestExecuteWithCpuLoop(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -699,7 +642,7 @@ func TestExecuteWithCpuLoop(t *testing.T) { require.NoError(t, err) _, _, bob := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, } @@ -729,16 +672,13 @@ func TestExecuteWithCpuLoop(t *testing.T) { } func TestExecuteWithStorageLoop(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -747,7 +687,7 @@ func TestExecuteWithStorageLoop(t *testing.T) { require.NoError(t, err) _, _, bob := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: bob, } @@ -776,15 +716,13 @@ func TestExecuteWithStorageLoop(t *testing.T) { } func TestMigrate(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, sdk.NewCoins(sdk.NewInt64Coin("denom", 5000))) + topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -797,7 +735,7 @@ func TestMigrate(t *testing.T) { _, _, anyAddr := keyPubAddr() _, _, newVerifierAddr := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: anyAddr, } @@ -896,17 +834,17 @@ func TestMigrate(t *testing.T) { assert.Equal(t, spec.codeID, cInfo.CodeID) expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.InitContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeInit, CodeID: originalCodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: initMsgBz, }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: spec.codeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: spec.migrateMsg, }} - assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, expHistory, keeper.GetContractHistory(ctx, contractAddr).CodeHistoryEntries) raw := keeper.QueryRaw(ctx, contractAddr, []byte("config")) var stored map[string][]byte @@ -919,15 +857,12 @@ func TestMigrate(t *testing.T) { } func TestMigrateWithDispatchedMessage(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, sdk.NewCoins(sdk.NewInt64Coin("denom", 5000))) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, sdk.NewCoins(sdk.NewInt64Coin("denom", 5000))) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -941,7 +876,7 @@ func TestMigrateWithDispatchedMessage(t *testing.T) { require.NotEqual(t, originalContractID, burnerContractID) _, _, myPayoutAddr := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: fred, } @@ -1001,7 +936,7 @@ func TestMigrateWithDispatchedMessage(t *testing.T) { require.Len(t, m, 0) // and all deposit tokens sent to myPayoutAddr - balance := accKeeper.GetAccount(ctx, myPayoutAddr).GetCoins() + balance := bankKeeper.GetAllBalances(ctx, myPayoutAddr) assert.Equal(t, deposit, balance) } @@ -1031,16 +966,13 @@ func mustMarshal(t *testing.T, r interface{}) []byte { } func TestUpdateContractAdmin(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -1049,7 +981,7 @@ func TestUpdateContractAdmin(t *testing.T) { require.NoError(t, err) _, _, anyAddr := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: anyAddr, } @@ -1106,16 +1038,13 @@ func TestUpdateContractAdmin(t *testing.T) { } func TestClearContractAdmin(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -1124,7 +1053,7 @@ func TestClearContractAdmin(t *testing.T) { require.NoError(t, err) _, _, anyAddr := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: fred, Beneficiary: anyAddr, } @@ -1173,35 +1102,3 @@ func TestClearContractAdmin(t *testing.T) { }) } } - -type InitMsg struct { - Verifier sdk.AccAddress `json:"verifier"` - Beneficiary sdk.AccAddress `json:"beneficiary"` -} - -func createFakeFundedAccount(ctx sdk.Context, am auth.AccountKeeper, coins sdk.Coins) sdk.AccAddress { - _, _, addr := keyPubAddr() - fundAccounts(ctx, am, addr, coins) - return addr -} - -func fundAccounts(ctx sdk.Context, am auth.AccountKeeper, addr sdk.AccAddress, coins sdk.Coins) { - baseAcct := auth.NewBaseAccountWithAddress(addr) - _ = baseAcct.SetCoins(coins) - am.SetAccount(ctx, &baseAcct) -} - -var keyCounter uint64 = 0 - -// we need to make this deterministic (same every test run), as encoded address size and thus gas cost, -// depends on the actual bytes (due to ugly CanonicalAddress encoding) -func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { - keyCounter++ - seed := make([]byte, 8) - binary.BigEndian.PutUint64(seed, keyCounter) - - key := ed25519.GenPrivKeyFromSecret(seed) - pub := key.PubKey() - addr := sdk.AccAddress(pub.Address()) - return key, pub, addr -} diff --git a/x/wasm/internal/keeper/legacy_querier.go b/x/wasm/internal/keeper/legacy_querier.go new file mode 100644 index 0000000000..906681111d --- /dev/null +++ b/x/wasm/internal/keeper/legacy_querier.go @@ -0,0 +1,120 @@ +package keeper + +import ( + "encoding/json" + "reflect" + "strconv" + + "github.com/CosmWasm/wasmd/x/wasm/internal/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + abci "github.com/tendermint/tendermint/abci/types" +) + +const ( + QueryListContractByCode = "list-contracts-by-code" + QueryGetContract = "contract-info" + QueryGetContractState = "contract-state" + QueryGetCode = "code" + QueryListCode = "list-code" + QueryContractHistory = "contract-history" +) + +const ( + QueryMethodContractStateSmart = "smart" + QueryMethodContractStateAll = "all" + QueryMethodContractStateRaw = "raw" +) + +// NewLegacyQuerier creates a new querier +func NewLegacyQuerier(keeper Keeper) sdk.Querier { + return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { + var ( + rsp interface{} + err error + ) + switch path[0] { + case QueryGetContract: + addr, err := sdk.AccAddressFromBech32(path[1]) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + } + rsp, err = queryContractInfo(ctx, addr, keeper) + case QueryListContractByCode: + codeID, err := strconv.ParseUint(path[1], 10, 64) + if err != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + } + rsp, err = queryContractListByCode(ctx, codeID, keeper) + case QueryGetContractState: + if len(path) < 3 { + return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") + } + return queryContractState(ctx, path[1], path[2], req.Data, keeper) + case QueryGetCode: + codeID, err := strconv.ParseUint(path[1], 10, 64) + if err != nil { + return nil, sdkerrors.Wrapf(types.ErrInvalid, "code id: %s", err.Error()) + } + rsp, err = queryCode(ctx, codeID, keeper) + case QueryListCode: + rsp, err = queryCodeList(ctx, keeper) + case QueryContractHistory: + contractAddr, err := sdk.AccAddressFromBech32(path[1]) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) + } + rsp, err = queryContractHistory(ctx, contractAddr, keeper) + default: + return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") + } + if err != nil { + return nil, err + } + if rsp == nil || reflect.ValueOf(rsp).IsNil() { + return nil, nil + } + bz, err := json.MarshalIndent(rsp, "", " ") + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + return bz, nil + } +} + +func queryContractState(ctx sdk.Context, bech, queryMethod string, data []byte, keeper Keeper) (json.RawMessage, error) { + contractAddr, err := sdk.AccAddressFromBech32(bech) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, bech) + } + + var resultData []types.Model + switch queryMethod { + case QueryMethodContractStateAll: + // this returns a serialized json object (which internally encoded binary fields properly) + for iter := keeper.GetContractState(ctx, contractAddr); iter.Valid(); iter.Next() { + resultData = append(resultData, types.Model{ + Key: iter.Key(), + Value: iter.Value(), + }) + } + if resultData == nil { + resultData = make([]types.Model, 0) + } + case QueryMethodContractStateRaw: + // this returns the raw data from the state, base64-encoded + return keeper.QueryRaw(ctx, contractAddr, data), nil + case QueryMethodContractStateSmart: + // we enforce a subjective gas limit on all queries to avoid infinite loops + ctx = ctx.WithGasMeter(sdk.NewGasMeter(keeper.queryGasLimit)) + // this returns raw bytes (must be base64-encoded) + return keeper.QuerySmart(ctx, contractAddr, data) + default: + return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, queryMethod) + } + bz, err := json.Marshal(resultData) + if err != nil { + return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + } + return bz, nil +} diff --git a/x/wasm/internal/keeper/legacy_querier_test.go b/x/wasm/internal/keeper/legacy_querier_test.go new file mode 100644 index 0000000000..81ffea5860 --- /dev/null +++ b/x/wasm/internal/keeper/legacy_querier_test.go @@ -0,0 +1,365 @@ +package keeper + +import ( + "bytes" + "encoding/json" + "fmt" + "io/ioutil" + "testing" + + "github.com/CosmWasm/wasmd/x/wasm/internal/types" + sdk "github.com/cosmos/cosmos-sdk/types" + sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + abci "github.com/tendermint/tendermint/abci/types" +) + +func TestLegacyQueryContractState(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper + + deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) + topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit.Add(deposit...)) + anyAddr := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) + + wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") + require.NoError(t, err) + + contractID, err := keeper.Create(ctx, creator, wasmCode, "", "", nil) + require.NoError(t, err) + + _, _, bob := keyPubAddr() + initMsg := HackatomExampleInitMsg{ + Verifier: anyAddr, + Beneficiary: bob, + } + initMsgBz, err := json.Marshal(initMsg) + require.NoError(t, err) + + addr, err := keeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract to query", deposit) + require.NoError(t, err) + + contractModel := []types.Model{ + {Key: []byte("foo"), Value: []byte(`"bar"`)}, + {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, + } + keeper.importContractState(ctx, addr, contractModel) + + // this gets us full error, not redacted sdk.Error + q := NewLegacyQuerier(keeper) + specs := map[string]struct { + srcPath []string + srcReq abci.RequestQuery + // smart and raw queries (not all queries) return raw bytes from contract not []types.Model + // if this is set, then we just compare - (should be json encoded string) + expRes []byte + // if success and expSmartRes is not set, we parse into []types.Model and compare (all state) + expModelLen int + expModelContains []types.Model + expErr *sdkErrors.Error + }{ + "query all": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateAll}, + expModelLen: 3, + expModelContains: []types.Model{ + {Key: []byte("foo"), Value: []byte(`"bar"`)}, + {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, + }, + }, + "query raw key": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, + srcReq: abci.RequestQuery{Data: []byte("foo")}, + expRes: []byte(`"bar"`), + }, + "query raw binary key": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, + srcReq: abci.RequestQuery{Data: []byte{0x0, 0x1}}, + expRes: []byte(`{"count":8}`), + }, + "query smart": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, + srcReq: abci.RequestQuery{Data: []byte(`{"verifier":{}}`)}, + expRes: []byte(fmt.Sprintf(`{"verifier":"%s"}`, anyAddr.String())), + }, + "query smart invalid request": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, + srcReq: abci.RequestQuery{Data: []byte(`{"raw":{"key":"config"}}`)}, + expErr: types.ErrQueryFailed, + }, + "query smart with invalid json": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, + srcReq: abci.RequestQuery{Data: []byte(`not a json string`)}, + expErr: types.ErrQueryFailed, + }, + "query non-existent raw key": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, + srcReq: abci.RequestQuery{Data: []byte("i do not exist")}, + expRes: nil, + }, + "query empty raw key": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, + srcReq: abci.RequestQuery{Data: []byte("")}, + expRes: nil, + }, + "query nil raw key": { + srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, + srcReq: abci.RequestQuery{Data: nil}, + expRes: nil, + }, + "query raw with unknown address": { + srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateRaw}, + expRes: nil, + }, + "query all with unknown address": { + srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateAll}, + expModelLen: 0, + }, + "query smart with unknown address": { + srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateSmart}, + expModelLen: 0, + expErr: types.ErrNotFound, + }, + } + + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + binResult, err := q(ctx, spec.srcPath, spec.srcReq) + // require.True(t, spec.expErr.Is(err), "unexpected error") + require.True(t, spec.expErr.Is(err), err) + + // if smart query, check custom response + if spec.srcPath[2] != QueryMethodContractStateAll { + require.Equal(t, spec.expRes, binResult) + return + } + + // otherwise, check returned models + var r []types.Model + if spec.expErr == nil { + require.NoError(t, json.Unmarshal(binResult, &r)) + require.NotNil(t, r) + } + require.Len(t, r, spec.expModelLen) + // and in result set + for _, v := range spec.expModelContains { + assert.Contains(t, r, v) + } + }) + } +} + +func TestLegacyQueryContractListByCodeOrdering(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper + + deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) + topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) + anyAddr := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) + + wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") + require.NoError(t, err) + + codeID, err := keeper.Create(ctx, creator, wasmCode, "", "", nil) + require.NoError(t, err) + + _, _, bob := keyPubAddr() + initMsg := HackatomExampleInitMsg{ + Verifier: anyAddr, + Beneficiary: bob, + } + initMsgBz, err := json.Marshal(initMsg) + require.NoError(t, err) + + // manage some realistic block settings + var h int64 = 10 + setBlock := func(ctx sdk.Context, height int64) sdk.Context { + ctx = ctx.WithBlockHeight(height) + meter := sdk.NewGasMeter(1000000) + ctx = ctx.WithGasMeter(meter) + ctx = ctx.WithBlockGasMeter(meter) + return ctx + } + + // create 10 contracts with real block/gas setup + for i := range [10]int{} { + // 3 tx per block, so we ensure both comparisons work + if i%3 == 0 { + ctx = setBlock(ctx, h) + h++ + } + _, err = keeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, fmt.Sprintf("contract %d", i), topUp) + require.NoError(t, err) + } + + // query and check the results are properly sorted + q := NewLegacyQuerier(keeper) + query := []string{QueryListContractByCode, fmt.Sprintf("%d", codeID)} + data := abci.RequestQuery{} + res, err := q(ctx, query, data) + require.NoError(t, err) + + var contracts []map[string]interface{} + err = json.Unmarshal(res, &contracts) + require.NoError(t, err) + + require.Equal(t, 10, len(contracts)) + + for i, contract := range contracts { + assert.Equal(t, fmt.Sprintf("contract %d", i), contract["label"]) + assert.NotEmpty(t, contract["address"]) + // ensure these are not shown + assert.Nil(t, contract["created"]) + } +} + +func TestLegacyQueryContractHistory(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + keeper := keepers.WasmKeeper + + var ( + otherAddr sdk.AccAddress = bytes.Repeat([]byte{0x2}, sdk.AddrLen) + ) + + specs := map[string]struct { + srcQueryAddr sdk.AccAddress + srcHistory []types.ContractCodeHistoryEntry + expContent []types.ContractCodeHistoryEntry + }{ + "response with internal fields cleared": { + srcHistory: []types.ContractCodeHistoryEntry{{ + Operation: types.ContractCodeHistoryTypeGenesis, + CodeID: firstCodeID, + Updated: types.NewAbsoluteTxPosition(ctx), + Msg: []byte(`"init message"`), + }}, + expContent: []types.ContractCodeHistoryEntry{{ + Operation: types.ContractCodeHistoryTypeGenesis, + CodeID: firstCodeID, + Msg: []byte(`"init message"`), + }}, + }, + "response with multiple entries": { + srcHistory: []types.ContractCodeHistoryEntry{{ + Operation: types.ContractCodeHistoryTypeInit, + CodeID: firstCodeID, + Updated: types.NewAbsoluteTxPosition(ctx), + Msg: []byte(`"init message"`), + }, { + Operation: types.ContractCodeHistoryTypeMigrate, + CodeID: 2, + Updated: types.NewAbsoluteTxPosition(ctx), + Msg: []byte(`"migrate message 1"`), + }, { + Operation: types.ContractCodeHistoryTypeMigrate, + CodeID: 3, + Updated: types.NewAbsoluteTxPosition(ctx), + Msg: []byte(`"migrate message 2"`), + }}, + expContent: []types.ContractCodeHistoryEntry{{ + Operation: types.ContractCodeHistoryTypeInit, + CodeID: firstCodeID, + Msg: []byte(`"init message"`), + }, { + Operation: types.ContractCodeHistoryTypeMigrate, + CodeID: 2, + Msg: []byte(`"migrate message 1"`), + }, { + Operation: types.ContractCodeHistoryTypeMigrate, + CodeID: 3, + Msg: []byte(`"migrate message 2"`), + }}, + }, + "unknown contract address": { + srcQueryAddr: otherAddr, + srcHistory: []types.ContractCodeHistoryEntry{{ + Operation: types.ContractCodeHistoryTypeGenesis, + CodeID: firstCodeID, + Updated: types.NewAbsoluteTxPosition(ctx), + Msg: []byte(`"init message"`), + }}, + expContent: nil, + }, + } + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + _, _, myContractAddr := keyPubAddr() + keeper.appendToContractHistory(ctx, myContractAddr, spec.srcHistory...) + q := NewLegacyQuerier(keeper) + queryContractAddr := spec.srcQueryAddr + if queryContractAddr == nil { + queryContractAddr = myContractAddr + } + + // when + query := []string{QueryContractHistory, queryContractAddr.String()} + data := abci.RequestQuery{} + resData, err := q(ctx, query, data) + + // then + require.NoError(t, err) + if spec.expContent == nil { + require.Nil(t, resData) + return + } + var got []types.ContractCodeHistoryEntry + err = json.Unmarshal(resData, &got) + require.NoError(t, err) + + assert.Equal(t, spec.expContent, got) + }) + } +} + +func TestLegacyQueryCodeList(t *testing.T) { + wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") + require.NoError(t, err) + + specs := map[string]struct { + codeIDs []uint64 + }{ + "none": {}, + "no gaps": { + codeIDs: []uint64{1, 2, 3}, + }, + "with gaps": { + codeIDs: []uint64{2, 4, 6}, + }, + } + + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + keeper := keepers.WasmKeeper + + for _, codeID := range spec.codeIDs { + require.NoError(t, keeper.importCode(ctx, codeID, + types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)), + wasmCode), + ) + } + q := NewLegacyQuerier(keeper) + // when + query := []string{QueryListCode} + data := abci.RequestQuery{} + resData, err := q(ctx, query, data) + + // then + require.NoError(t, err) + if len(spec.codeIDs) == 0 { + require.Nil(t, resData) + return + } + + var got []map[string]interface{} + err = json.Unmarshal(resData, &got) + require.NoError(t, err) + require.Len(t, got, len(spec.codeIDs)) + for i, exp := range spec.codeIDs { + assert.EqualValues(t, exp, got[i]["id"]) + } + }) + } +} diff --git a/x/wasm/internal/keeper/proposal_handler.go b/x/wasm/internal/keeper/proposal_handler.go index 047c292316..5e5c39e7b8 100644 --- a/x/wasm/internal/keeper/proposal_handler.go +++ b/x/wasm/internal/keeper/proposal_handler.go @@ -23,16 +23,16 @@ func NewWasmProposalHandler(k Keeper, enabledProposalTypes []types.ProposalType) return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unsupported wasm proposal content type: %q", content.ProposalType()) } switch c := content.(type) { - case types.StoreCodeProposal: - return handleStoreCodeProposal(ctx, k, c) - case types.InstantiateContractProposal: - return handleInstantiateProposal(ctx, k, c) - case types.MigrateContractProposal: - return handleMigrateProposal(ctx, k, c) - case types.UpdateAdminProposal: - return handleUpdateAdminProposal(ctx, k, c) - case types.ClearAdminProposal: - return handleClearAdminProposal(ctx, k, c) + case *types.StoreCodeProposal: + return handleStoreCodeProposal(ctx, k, *c) + case *types.InstantiateContractProposal: + return handleInstantiateProposal(ctx, k, *c) + case *types.MigrateContractProposal: + return handleMigrateProposal(ctx, k, *c) + case *types.UpdateAdminProposal: + return handleUpdateAdminProposal(ctx, k, *c) + case *types.ClearAdminProposal: + return handleClearAdminProposal(ctx, k, *c) default: return sdkerrors.Wrapf(sdkerrors.ErrUnknownRequest, "unrecognized wasm proposal content type: %T", c) } @@ -93,7 +93,15 @@ func handleMigrateProposal(ctx sdk.Context, k Keeper, p types.MigrateContractPro sdk.NewAttribute(sdk.AttributeKeyModule, types.ModuleName), sdk.NewAttribute(types.AttributeKeyContract, p.Contract.String()), ) - ctx.EventManager().EmitEvents(append(res.Events, ourEvent)) + ctx.EventManager().EmitEvent(ourEvent) + + for _, e := range res.Events { + attr := make([]sdk.Attribute, len(e.Attributes)) + for i, a := range e.Attributes { + attr[i] = sdk.NewAttribute(string(a.Key), string(a.Value)) + } + ctx.EventManager().EmitEvent(sdk.NewEvent(e.Type, attr...)) + } return nil } diff --git a/x/wasm/internal/keeper/proposal_integration_test.go b/x/wasm/internal/keeper/proposal_integration_test.go index 8d99dbf2d2..c3cdf1b1d0 100644 --- a/x/wasm/internal/keeper/proposal_integration_test.go +++ b/x/wasm/internal/keeper/proposal_integration_test.go @@ -5,25 +5,20 @@ import ( "encoding/hex" "encoding/json" "io/ioutil" - "os" "testing" "github.com/CosmWasm/wasmd/x/wasm/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" - "github.com/cosmos/cosmos-sdk/x/params" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" + "github.com/cosmos/cosmos-sdk/x/params/types/proposal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestStoreCodeProposal(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.setParams(ctx, types.Params{UploadAccess: types.AllowNobody, DefaultInstantiatePermission: types.Nobody}) + wasmKeeper.setParams(ctx, types.Params{CodeUploadAccess: types.AllowNobody, InstantiateDefaultPermission: types.AccessTypeNobody}) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -42,7 +37,7 @@ func TestStoreCodeProposal(t *testing.T) { // and proposal execute handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.Content) + err = handler(ctx, storedProposal.GetContent()) require.NoError(t, err) // then @@ -58,13 +53,9 @@ func TestStoreCodeProposal(t *testing.T) { } func TestInstantiateProposal(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.setParams(ctx, types.Params{UploadAccess: types.AllowNobody, DefaultInstantiatePermission: types.Nobody}) + wasmKeeper.setParams(ctx, types.Params{CodeUploadAccess: types.AllowNobody, InstantiateDefaultPermission: types.AccessTypeNobody}) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -91,7 +82,7 @@ func TestInstantiateProposal(t *testing.T) { // and proposal execute handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.Content) + err = handler(ctx, storedProposal.GetContent()) require.NoError(t, err) // then @@ -105,22 +96,18 @@ func TestInstantiateProposal(t *testing.T) { assert.Equal(t, otherAddress, cInfo.Admin) assert.Equal(t, "testing", cInfo.Label) expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.InitContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeInit, CodeID: src.CodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: src.InitMsg, }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr).CodeHistoryEntries) } func TestMigrateProposal(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.setParams(ctx, types.Params{UploadAccess: types.AllowNobody, DefaultInstantiatePermission: types.Nobody}) + wasmKeeper.setParams(ctx, types.Params{CodeUploadAccess: types.AllowNobody, InstantiateDefaultPermission: types.AccessTypeNobody}) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -151,23 +138,21 @@ func TestMigrateProposal(t *testing.T) { require.NoError(t, err) src := types.MigrateContractProposal{ - WasmProposal: types.WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - CodeID: 2, - Contract: contractAddr, - MigrateMsg: migMsgBz, - RunAs: otherAddress, + Title: "Foo", + Description: "Bar", + CodeID: 2, + Contract: contractAddr, + MigrateMsg: migMsgBz, + RunAs: otherAddress, } // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, src) + storedProposal, err := govKeeper.SubmitProposal(ctx, &src) require.NoError(t, err) // and proposal execute handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.Content) + err = handler(ctx, storedProposal.GetContent()) require.NoError(t, err) // then @@ -178,16 +163,16 @@ func TestMigrateProposal(t *testing.T) { assert.Equal(t, anyAddress, cInfo.Admin) assert.Equal(t, "testing", cInfo.Label) expHistory := []types.ContractCodeHistoryEntry{{ - Operation: types.GenesisContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeGenesis, CodeID: firstCodeID, Updated: types.NewAbsoluteTxPosition(ctx), }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: src.CodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: src.MigrateMsg, }} - assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr)) + assert.Equal(t, expHistory, wasmKeeper.GetContractHistory(ctx, contractAddr).CodeHistoryEntries) } @@ -201,18 +186,16 @@ func TestAdminProposals(t *testing.T) { specs := map[string]struct { state types.ContractInfo - srcProposal gov.Content + srcProposal govtypes.Content expAdmin sdk.AccAddress }{ "update with different admin": { state: types.ContractInfoFixture(), - srcProposal: types.UpdateAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, - NewAdmin: otherAddress, + srcProposal: &types.UpdateAdminProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, + NewAdmin: otherAddress, }, expAdmin: otherAddress, }, @@ -220,24 +203,20 @@ func TestAdminProposals(t *testing.T) { state: types.ContractInfoFixture(func(info *types.ContractInfo) { info.Admin = nil }), - srcProposal: types.UpdateAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, - NewAdmin: otherAddress, + srcProposal: &types.UpdateAdminProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, + NewAdmin: otherAddress, }, expAdmin: otherAddress, }, "clear admin": { state: types.ContractInfoFixture(), - srcProposal: types.ClearAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, + srcProposal: &types.ClearAdminProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, }, expAdmin: nil, }, @@ -245,24 +224,19 @@ func TestAdminProposals(t *testing.T) { state: types.ContractInfoFixture(func(info *types.ContractInfo) { info.Admin = nil }), - srcProposal: types.ClearAdminProposal{ - WasmProposal: types.WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, + srcProposal: &types.ClearAdminProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, }, expAdmin: nil, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper - wasmKeeper.setParams(ctx, types.Params{UploadAccess: types.AllowNobody, DefaultInstantiatePermission: types.Nobody}) + wasmKeeper.setParams(ctx, types.Params{CodeUploadAccess: types.AllowNobody, InstantiateDefaultPermission: types.AccessTypeNobody}) codeInfoFixture := types.CodeInfoFixture(types.WithSHA256CodeHash(wasmCode)) require.NoError(t, wasmKeeper.importCode(ctx, 1, codeInfoFixture, wasmCode)) @@ -274,7 +248,7 @@ func TestAdminProposals(t *testing.T) { // and execute proposal handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.Content) + err = handler(ctx, storedProposal.GetContent()) require.NoError(t, err) // then @@ -286,69 +260,67 @@ func TestAdminProposals(t *testing.T) { } func TestUpdateParamsProposal(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) govKeeper, wasmKeeper := keepers.GovKeeper, keepers.WasmKeeper var ( cdc = keepers.WasmKeeper.cdc myAddress sdk.AccAddress = make([]byte, sdk.AddrLen) - oneAddressAccessConfig = types.OnlyAddress.With(myAddress) + oneAddressAccessConfig = types.AccessTypeOnlyAddress.With(myAddress) ) + nobodyJson, err := json.Marshal(types.AccessTypeNobody) + require.NoError(t, err) specs := map[string]struct { - src params.ParamChange + src proposal.ParamChange expUploadConfig types.AccessConfig expInstantiateType types.AccessType }{ "update upload permission param": { - src: params.ParamChange{ + src: proposal.ParamChange{ Subspace: types.DefaultParamspace, Key: string(types.ParamStoreKeyUploadAccess), Value: string(cdc.MustMarshalJSON(&types.AllowNobody)), }, expUploadConfig: types.AllowNobody, - expInstantiateType: types.Everybody, + expInstantiateType: types.AccessTypeEverybody, }, "update upload permission param with address": { - src: params.ParamChange{ + src: proposal.ParamChange{ Subspace: types.DefaultParamspace, Key: string(types.ParamStoreKeyUploadAccess), Value: string(cdc.MustMarshalJSON(&oneAddressAccessConfig)), }, expUploadConfig: oneAddressAccessConfig, - expInstantiateType: types.Everybody, + expInstantiateType: types.AccessTypeEverybody, }, "update instantiate param": { - src: params.ParamChange{ + src: proposal.ParamChange{ Subspace: types.DefaultParamspace, Key: string(types.ParamStoreKeyInstantiateAccess), - Value: string(cdc.MustMarshalJSON(types.Nobody)), + Value: string(nobodyJson), }, expUploadConfig: types.AllowEverybody, - expInstantiateType: types.Nobody, + expInstantiateType: types.AccessTypeNobody, }, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { wasmKeeper.setParams(ctx, types.DefaultParams()) - proposal := params.ParameterChangeProposal{ + proposal := proposal.ParameterChangeProposal{ Title: "Foo", Description: "Bar", - Changes: []params.ParamChange{spec.src}, + Changes: []proposal.ParamChange{spec.src}, } // when stored - storedProposal, err := govKeeper.SubmitProposal(ctx, proposal) + storedProposal, err := govKeeper.SubmitProposal(ctx, &proposal) require.NoError(t, err) // and proposal execute handler := govKeeper.Router().GetRoute(storedProposal.ProposalRoute()) - err = handler(ctx, storedProposal.Content) + err = handler(ctx, storedProposal.GetContent()) require.NoError(t, err) // then diff --git a/x/wasm/internal/keeper/querier.go b/x/wasm/internal/keeper/querier.go index ab8232064e..14570e7b0e 100644 --- a/x/wasm/internal/keeper/querier.go +++ b/x/wasm/internal/keeper/querier.go @@ -1,102 +1,168 @@ package keeper import ( - "encoding/json" + "context" "sort" - "strconv" "github.com/CosmWasm/wasmd/x/wasm/internal/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - - abci "github.com/tendermint/tendermint/abci/types" - tmbytes "github.com/tendermint/tendermint/libs/bytes" + "github.com/golang/protobuf/ptypes/empty" ) -const ( - QueryListContractByCode = "list-contracts-by-code" - QueryGetContract = "contract-info" - QueryGetContractState = "contract-state" - QueryGetCode = "code" - QueryListCode = "list-code" - QueryContractHistory = "contract-history" -) +type grpcQuerier struct { + keeper Keeper +} -const ( - QueryMethodContractStateSmart = "smart" - QueryMethodContractStateAll = "all" - QueryMethodContractStateRaw = "raw" -) +// todo: this needs proper tests and doc +func NewQuerier(keeper Keeper) grpcQuerier { + return grpcQuerier{keeper: keeper} +} -// ContractInfoWithAddress adds the address (key) to the ContractInfo representation -type ContractInfoWithAddress struct { - // embedded here, so all json items remain top level - *types.ContractInfo - Address sdk.AccAddress `json:"address"` +func (q grpcQuerier) ContractInfo(c context.Context, req *types.QueryContractInfoRequest) (*types.QueryContractInfoResponse, error) { + if err := sdk.VerifyAddressFormat(req.Address); err != nil { + return nil, err + } + rsp, err := queryContractInfo(sdk.UnwrapSDKContext(c), req.Address, q.keeper) + switch { + case err != nil: + return nil, err + case rsp == nil: + return nil, types.ErrNotFound + } + return &types.QueryContractInfoResponse{ + Address: rsp.Address, + ContractInfo: rsp.ContractInfo, + }, nil } -// NewQuerier creates a new querier -func NewQuerier(keeper Keeper) sdk.Querier { - return func(ctx sdk.Context, path []string, req abci.RequestQuery) ([]byte, error) { - switch path[0] { - case QueryGetContract: - return queryContractInfo(ctx, path[1], keeper) - case QueryListContractByCode: - return queryContractListByCode(ctx, path[1], keeper) - case QueryGetContractState: - if len(path) < 3 { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") - } - return queryContractState(ctx, path[1], path[2], req, keeper) - case QueryGetCode: - return queryCode(ctx, path[1], keeper) - case QueryListCode: - return queryCodeList(ctx, keeper) - case QueryContractHistory: - return queryContractHistory(ctx, path[1], keeper) - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "unknown data query endpoint") - } +func (q grpcQuerier) ContractHistory(c context.Context, req *types.QueryContractHistoryRequest) (*types.QueryContractHistoryResponse, error) { + if err := sdk.VerifyAddressFormat(req.Address); err != nil { + return nil, err + } + rsp, err := queryContractHistory(sdk.UnwrapSDKContext(c), req.Address, q.keeper) + switch { + case err != nil: + return nil, err + case rsp == nil: + return nil, types.ErrNotFound } + return &types.QueryContractHistoryResponse{ + Entries: rsp, + }, nil } -func queryContractInfo(ctx sdk.Context, bech string, keeper Keeper) ([]byte, error) { - addr, err := sdk.AccAddressFromBech32(bech) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) +func (q grpcQuerier) ContractsByCode(c context.Context, req *types.QueryContractsByCodeRequest) (*types.QueryContractsByCodeResponse, error) { + if req.CodeId == 0 { + return nil, sdkerrors.Wrap(types.ErrInvalid, "code id") } - info := keeper.GetContractInfo(ctx, addr) - if info == nil { - return []byte("null"), nil + rsp, err := queryContractListByCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper) + switch { + case err != nil: + return nil, err + case rsp == nil: + return nil, types.ErrNotFound } - redact(info) - infoWithAddress := ContractInfoWithAddress{ - Address: addr, - ContractInfo: info, + return &types.QueryContractsByCodeResponse{ + ContractInfos: rsp, + }, nil +} + +func (q grpcQuerier) AllContractState(c context.Context, req *types.QueryAllContractStateRequest) (*types.QueryAllContractStateResponse, error) { + if err := sdk.VerifyAddressFormat(req.Address); err != nil { + return nil, err } - bz, err := json.MarshalIndent(infoWithAddress, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + ctx := sdk.UnwrapSDKContext(c) + if !q.keeper.containsContractInfo(ctx, req.Address) { + return nil, types.ErrNotFound + } + var resultData []types.Model + for iter := q.keeper.GetContractState(ctx, req.Address); iter.Valid(); iter.Next() { + resultData = append(resultData, types.Model{ + Key: iter.Key(), + Value: iter.Value(), + }) } - return bz, nil + return &types.QueryAllContractStateResponse{Models: resultData}, nil } -// redact clears all fields not in the public api -func redact(info *types.ContractInfo) { - info.Created = nil +func (q grpcQuerier) RawContractState(c context.Context, req *types.QueryRawContractStateRequest) (*types.QueryRawContractStateResponse, error) { + ctx := sdk.UnwrapSDKContext(c) + + if err := sdk.VerifyAddressFormat(req.Address); err != nil { + return nil, err + } + + if !q.keeper.containsContractInfo(ctx, req.Address) { + return nil, types.ErrNotFound + } + rsp := q.keeper.QueryRaw(ctx, req.Address, req.QueryData) + return &types.QueryRawContractStateResponse{Data: rsp}, nil } -func queryContractListByCode(ctx sdk.Context, codeIDstr string, keeper Keeper) ([]byte, error) { - codeID, err := strconv.ParseUint(codeIDstr, 10, 64) - if err != nil { +func (q grpcQuerier) SmartContractState(c context.Context, req *types.QuerySmartContractStateRequest) (*types.QuerySmartContractStateResponse, error) { + if err := sdk.VerifyAddressFormat(req.Address); err != nil { + return nil, err + } + ctx := sdk.UnwrapSDKContext(c).WithGasMeter(sdk.NewGasMeter(q.keeper.queryGasLimit)) + rsp, err := q.keeper.QuerySmart(ctx, req.Address, req.QueryData) + switch { + case err != nil: + return nil, err + case rsp == nil: + return nil, types.ErrNotFound + } + return &types.QuerySmartContractStateResponse{Data: rsp}, nil + +} + +func (q grpcQuerier) Code(c context.Context, req *types.QueryCodeRequest) (*types.QueryCodeResponse, error) { + if req.CodeId == 0 { + return nil, sdkerrors.Wrap(types.ErrInvalid, "code id") + } + rsp, err := queryCode(sdk.UnwrapSDKContext(c), req.CodeId, q.keeper) + switch { + case err != nil: + return nil, err + case rsp == nil: + return nil, types.ErrNotFound + } + return &types.QueryCodeResponse{ + CodeInfoResponse: rsp.CodeInfoResponse, + Data: rsp.Data, + }, nil +} + +func (q grpcQuerier) Codes(c context.Context, _ *empty.Empty) (*types.QueryCodesResponse, error) { + rsp, err := queryCodeList(sdk.UnwrapSDKContext(c), q.keeper) + switch { + case err != nil: return nil, err + case rsp == nil: + return nil, types.ErrNotFound } + return &types.QueryCodesResponse{CodeInfos: rsp}, nil +} + +func queryContractInfo(ctx sdk.Context, addr sdk.AccAddress, keeper Keeper) (*types.ContractInfoWithAddress, error) { + info := keeper.GetContractInfo(ctx, addr) + if info == nil { + return nil, types.ErrNotFound + } + // redact the Created field (just used for sorting, not part of public API) + info.Created = nil + return &types.ContractInfoWithAddress{ + Address: addr, + ContractInfo: info, + }, nil +} - var contracts []ContractInfoWithAddress +func queryContractListByCode(ctx sdk.Context, codeID uint64, keeper Keeper) ([]types.ContractInfoWithAddress, error) { + var contracts []types.ContractInfoWithAddress keeper.IterateContractInfo(ctx, func(addr sdk.AccAddress, info types.ContractInfo) bool { if info.CodeID == codeID { // and add the address - infoWithAddress := ContractInfoWithAddress{ + infoWithAddress := types.ContractInfoWithAddress{ Address: addr, ContractInfo: &info, } @@ -109,74 +175,24 @@ func queryContractListByCode(ctx sdk.Context, codeIDstr string, keeper Keeper) ( sort.Slice(contracts, func(i, j int) bool { return contracts[i].ContractInfo.Created.LessThan(contracts[j].ContractInfo.Created) }) - // and remove that info for the final json (yes, the json:"-" tag doesn't work) - for i := range contracts { - redact(contracts[i].ContractInfo) - } - bz, err := json.MarshalIndent(contracts, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil -} - -func queryContractState(ctx sdk.Context, bech, queryMethod string, req abci.RequestQuery, keeper Keeper) ([]byte, error) { - contractAddr, err := sdk.AccAddressFromBech32(bech) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, bech) - } - - var resultData []types.Model - switch queryMethod { - case QueryMethodContractStateAll: - // this returns a serialized json object (which internally encoded binary fields properly) - for iter := keeper.GetContractState(ctx, contractAddr); iter.Valid(); iter.Next() { - resultData = append(resultData, types.Model{ - Key: iter.Key(), - Value: iter.Value(), - }) - } - if resultData == nil { - resultData = make([]types.Model, 0) - } - case QueryMethodContractStateRaw: - // this returns the raw data from the state, base64-encoded - return keeper.QueryRaw(ctx, contractAddr, req.Data), nil - case QueryMethodContractStateSmart: - // we enforce a subjective gas limit on all queries to avoid infinite loops - ctx = ctx.WithGasMeter(sdk.NewGasMeter(keeper.queryGasLimit)) - // this returns raw bytes (must be base64-encoded) - return keeper.QuerySmart(ctx, contractAddr, req.Data) - default: - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, queryMethod) - } - bz, err := json.Marshal(resultData) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + for i := range contracts { + contracts[i].Created = nil } - return bz, nil -} - -type GetCodeResponse struct { - ListCodeResponse - // Data is the entire wasm bytecode - Data []byte `json:"data" yaml:"data"` + return contracts, nil } -func queryCode(ctx sdk.Context, codeIDstr string, keeper Keeper) ([]byte, error) { - codeID, err := strconv.ParseUint(codeIDstr, 10, 64) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrUnknownRequest, "invalid codeID: "+err.Error()) +func queryCode(ctx sdk.Context, codeID uint64, keeper Keeper) (*types.QueryCodeResponse, error) { + if codeID == 0 { + return nil, nil } - res := keeper.GetCodeInfo(ctx, codeID) if res == nil { // nil, nil leads to 404 in rest handler return nil, nil } - info := ListCodeResponse{ - ID: codeID, + info := types.CodeInfoResponse{ + CodeID: codeID, Creator: res.Creator, DataHash: res.CodeHash, Source: res.Source, @@ -188,26 +204,14 @@ func queryCode(ctx sdk.Context, codeIDstr string, keeper Keeper) ([]byte, error) return nil, sdkerrors.Wrap(err, "loading wasm code") } - bz, err := json.MarshalIndent(GetCodeResponse{info, code}, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil + return &types.QueryCodeResponse{CodeInfoResponse: &info, Data: code}, nil } -type ListCodeResponse struct { - ID uint64 `json:"id"` - Creator sdk.AccAddress `json:"creator"` - DataHash tmbytes.HexBytes `json:"data_hash"` - Source string `json:"source"` - Builder string `json:"builder"` -} - -func queryCodeList(ctx sdk.Context, keeper Keeper) ([]byte, error) { - var info []ListCodeResponse +func queryCodeList(ctx sdk.Context, keeper Keeper) ([]types.CodeInfoResponse, error) { + var info []types.CodeInfoResponse keeper.IterateCodeInfos(ctx, func(i uint64, res types.CodeInfo) bool { - info = append(info, ListCodeResponse{ - ID: i, + info = append(info, types.CodeInfoResponse{ + CodeID: i, Creator: res.Creator, DataHash: res.CodeHash, Source: res.Source, @@ -215,32 +219,18 @@ func queryCodeList(ctx sdk.Context, keeper Keeper) ([]byte, error) { }) return false }) - - bz, err := json.MarshalIndent(info, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) - } - return bz, nil + return info, nil } -func queryContractHistory(ctx sdk.Context, bech string, keeper Keeper) ([]byte, error) { - contractAddr, err := sdk.AccAddressFromBech32(bech) - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, err.Error()) - } - entries := keeper.GetContractHistory(ctx, contractAddr) - if entries == nil { +func queryContractHistory(ctx sdk.Context, contractAddr sdk.AccAddress, keeper Keeper) ([]types.ContractCodeHistoryEntry, error) { + history := keeper.GetContractHistory(ctx, contractAddr) + if history.CodeHistoryEntries == nil { // nil, nil leads to 404 in rest handler return nil, nil } // redact response - for i := range entries { - entries[i].Updated = nil - } - - bz, err := json.MarshalIndent(entries, "", " ") - if err != nil { - return nil, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + for i := range history.CodeHistoryEntries { + history.CodeHistoryEntries[i].Updated = nil } - return bz, nil + return history.CodeHistoryEntries, nil } diff --git a/x/wasm/internal/keeper/querier_test.go b/x/wasm/internal/keeper/querier_test.go index 7f005102ca..7301956dae 100644 --- a/x/wasm/internal/keeper/querier_test.go +++ b/x/wasm/internal/keeper/querier_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io/ioutil" - "os" "testing" "github.com/CosmWasm/wasmd/x/wasm/internal/types" @@ -13,158 +12,155 @@ import ( sdkErrors "github.com/cosmos/cosmos-sdk/types/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" ) -func TestQueryContractState(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper - - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - anyAddr := createFakeFundedAccount(ctx, accKeeper, topUp) - - wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - - contractID, err := keeper.Create(ctx, creator, wasmCode, "", "", nil) - require.NoError(t, err) - - _, _, bob := keyPubAddr() - initMsg := InitMsg{ - Verifier: anyAddr, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - - addr, err := keeper.Instantiate(ctx, contractID, creator, nil, initMsgBz, "demo contract to query", deposit) - require.NoError(t, err) +func TestQueryAllContractState(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + keeper := keepers.WasmKeeper + exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) + contractAddr := exampleContract.Contract contractModel := []types.Model{ {Key: []byte("foo"), Value: []byte(`"bar"`)}, {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, } - keeper.importContractState(ctx, addr, contractModel) + require.NoError(t, keeper.importContractState(ctx, contractAddr, contractModel)) - // this gets us full error, not redacted sdk.Error q := NewQuerier(keeper) specs := map[string]struct { - srcPath []string - srcReq abci.RequestQuery - // smart and raw queries (not all queries) return raw bytes from contract not []types.Model - // if this is set, then we just compare - (should be json encoded string) - expRes []byte - // if success and expSmartRes is not set, we parse into []types.Model and compare (all state) - expModelLen int + srcQuery *types.QueryAllContractStateRequest expModelContains []types.Model expErr *sdkErrors.Error }{ "query all": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateAll}, - expModelLen: 3, - expModelContains: []types.Model{ - {Key: []byte("foo"), Value: []byte(`"bar"`)}, - {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, - }, + srcQuery: &types.QueryAllContractStateRequest{Address: contractAddr}, + expModelContains: contractModel, }, - "query raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("foo")}, - expRes: []byte(`"bar"`), - }, - "query raw binary key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte{0x0, 0x1}}, - expRes: []byte(`{"count":8}`), + "query all with unknown address": { + srcQuery: &types.QueryAllContractStateRequest{Address: AnyAccAddress(t)}, + expErr: types.ErrNotFound, }, + } + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + got, err := q.AllContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) + require.True(t, spec.expErr.Is(err), err) + if spec.expErr != nil { + return + } + for _, exp := range spec.expModelContains { + assert.Contains(t, got.Models, exp) + } + }) + } +} + +func TestQuerySmartContractState(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + keeper := keepers.WasmKeeper + + exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) + contractAddr := exampleContract.Contract + + q := NewQuerier(keeper) + specs := map[string]struct { + srcAddr sdk.AccAddress + srcQuery *types.QuerySmartContractStateRequest + expResp string + expErr *sdkErrors.Error + }{ "query smart": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`{"verifier":{}}`)}, - expRes: []byte(fmt.Sprintf(`{"verifier":"%s"}`, anyAddr.String())), + srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"verifier":{}}`)}, + expResp: fmt.Sprintf(`{"verifier":"%s"}`, exampleContract.VerifierAddr.String()), }, "query smart invalid request": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`{"raw":{"key":"config"}}`)}, - expErr: types.ErrQueryFailed, + srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`{"raw":{"key":"config"}}`)}, + expErr: types.ErrQueryFailed, }, "query smart with invalid json": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateSmart}, - srcReq: abci.RequestQuery{Data: []byte(`not a json string`)}, - expErr: types.ErrQueryFailed, + srcQuery: &types.QuerySmartContractStateRequest{Address: contractAddr, QueryData: []byte(`not a json string`)}, + expErr: types.ErrQueryFailed, + }, + "query smart with unknown address": { + srcQuery: &types.QuerySmartContractStateRequest{Address: AnyAccAddress(t), QueryData: []byte(`{"verifier":{}}`)}, + expErr: types.ErrNotFound, + }, + } + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + got, err := q.SmartContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) + require.True(t, spec.expErr.Is(err), err) + if spec.expErr != nil { + return + } + assert.JSONEq(t, string(got.Data), spec.expResp) + }) + } +} + +func TestQueryRawContractState(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + keeper := keepers.WasmKeeper + + exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) + contractAddr := exampleContract.Contract + contractModel := []types.Model{ + {Key: []byte("foo"), Value: []byte(`"bar"`)}, + {Key: []byte{0x0, 0x1}, Value: []byte(`{"count":8}`)}, + } + require.NoError(t, keeper.importContractState(ctx, contractAddr, contractModel)) + + q := NewQuerier(keeper) + specs := map[string]struct { + srcQuery *types.QueryRawContractStateRequest + expData []byte + expErr *sdkErrors.Error + }{ + "query raw key": { + srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("foo")}, + expData: []byte(`"bar"`), + }, + "query raw binary key": { + srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte{0x0, 0x1}}, + expData: []byte(`{"count":8}`), }, "query non-existent raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("i do not exist")}, - expRes: nil, + srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("not existing key")}, + expData: nil, }, "query empty raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: []byte("")}, - expRes: nil, + srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr, QueryData: []byte("")}, + expData: nil, }, "query nil raw key": { - srcPath: []string{QueryGetContractState, addr.String(), QueryMethodContractStateRaw}, - srcReq: abci.RequestQuery{Data: nil}, - expRes: nil, + srcQuery: &types.QueryRawContractStateRequest{Address: contractAddr}, + expData: nil, }, "query raw with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateRaw}, - expRes: nil, - }, - "query all with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateAll}, - expModelLen: 0, - }, - "query smart with unknown address": { - srcPath: []string{QueryGetContractState, anyAddr.String(), QueryMethodContractStateSmart}, - expModelLen: 0, - expErr: types.ErrNotFound, + srcQuery: &types.QueryRawContractStateRequest{Address: AnyAccAddress(t), QueryData: []byte("foo")}, + expErr: types.ErrNotFound, }, } - for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - binResult, err := q(ctx, spec.srcPath, spec.srcReq) - // require.True(t, spec.expErr.Is(err), "unexpected error") + got, err := q.RawContractState(sdk.WrapSDKContext(ctx), spec.srcQuery) require.True(t, spec.expErr.Is(err), err) - - // if smart query, check custom response - if spec.srcPath[2] != QueryMethodContractStateAll { - require.Equal(t, spec.expRes, binResult) + if spec.expErr != nil { return } - - // otherwise, check returned models - var r []types.Model - if spec.expErr == nil { - require.NoError(t, json.Unmarshal(binResult, &r)) - require.NotNil(t, r) - } - require.Len(t, r, spec.expModelLen) - // and in result set - for _, v := range spec.expModelContains { - assert.Contains(t, r, v) - } + assert.Equal(t, spec.expData, got.Data) }) } } -func TestListContractByCodeOrdering(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper +func TestQueryContractListByCodeOrdering(t *testing.T) { + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 500)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) - anyAddr := createFakeFundedAccount(ctx, accKeeper, topUp) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) + anyAddr := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, topUp) wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") require.NoError(t, err) @@ -173,7 +169,7 @@ func TestListContractByCodeOrdering(t *testing.T) { require.NoError(t, err) _, _, bob := keyPubAddr() - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: anyAddr, Beneficiary: bob, } @@ -203,18 +199,12 @@ func TestListContractByCodeOrdering(t *testing.T) { // query and check the results are properly sorted q := NewQuerier(keeper) - query := []string{QueryListContractByCode, fmt.Sprintf("%d", codeID)} - data := abci.RequestQuery{} - res, err := q(ctx, query, data) + res, err := q.ContractsByCode(sdk.WrapSDKContext(ctx), &types.QueryContractsByCodeRequest{CodeId: codeID}) require.NoError(t, err) - var contracts []ContractInfoWithAddress - err = json.Unmarshal(res, &contracts) - require.NoError(t, err) + require.Equal(t, 10, len(res.ContractInfos)) - require.Equal(t, 10, len(contracts)) - - for i, contract := range contracts { + for i, contract := range res.ContractInfos { assert.Equal(t, fmt.Sprintf("contract %d", i), contract.Label) assert.NotEmpty(t, contract.Address) // ensure these are not shown @@ -223,10 +213,7 @@ func TestListContractByCodeOrdering(t *testing.T) { } func TestQueryContractHistory(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) keeper := keepers.WasmKeeper var ( @@ -240,44 +227,44 @@ func TestQueryContractHistory(t *testing.T) { }{ "response with internal fields cleared": { srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.GenesisContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeGenesis, CodeID: firstCodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: []byte(`"init message"`), }}, expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.GenesisContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeGenesis, CodeID: firstCodeID, Msg: []byte(`"init message"`), }}, }, "response with multiple entries": { srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.InitContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeInit, CodeID: firstCodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: []byte(`"init message"`), }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: 2, Updated: types.NewAbsoluteTxPosition(ctx), Msg: []byte(`"migrate message 1"`), }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: 3, Updated: types.NewAbsoluteTxPosition(ctx), Msg: []byte(`"migrate message 2"`), }}, expContent: []types.ContractCodeHistoryEntry{{ - Operation: types.InitContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeInit, CodeID: firstCodeID, Msg: []byte(`"init message"`), }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: 2, Msg: []byte(`"migrate message 1"`), }, { - Operation: types.MigrateContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeMigrate, CodeID: 3, Msg: []byte(`"migrate message 2"`), }}, @@ -285,7 +272,7 @@ func TestQueryContractHistory(t *testing.T) { "unknown contract address": { srcQueryAddr: otherAddr, srcHistory: []types.ContractCodeHistoryEntry{{ - Operation: types.GenesisContractCodeHistoryType, + Operation: types.ContractCodeHistoryTypeGenesis, CodeID: firstCodeID, Updated: types.NewAbsoluteTxPosition(ctx), Msg: []byte(`"init message"`), @@ -297,28 +284,24 @@ func TestQueryContractHistory(t *testing.T) { t.Run(msg, func(t *testing.T) { _, _, myContractAddr := keyPubAddr() keeper.appendToContractHistory(ctx, myContractAddr, spec.srcHistory...) - q := NewQuerier(keeper) + queryContractAddr := spec.srcQueryAddr if queryContractAddr == nil { queryContractAddr = myContractAddr } + req := &types.QueryContractHistoryRequest{Address: queryContractAddr} // when - query := []string{QueryContractHistory, queryContractAddr.String()} - data := abci.RequestQuery{} - resData, err := q(ctx, query, data) + q := NewQuerier(keeper) + got, err := q.ContractHistory(sdk.WrapSDKContext(ctx), req) // then - require.NoError(t, err) if spec.expContent == nil { - require.Nil(t, resData) + require.Error(t, types.ErrEmpty) return } - var got []types.ContractCodeHistoryEntry - err = json.Unmarshal(resData, &got) require.NoError(t, err) - - assert.Equal(t, spec.expContent, got) + assert.Equal(t, spec.expContent, got.Entries) }) } } @@ -341,10 +324,7 @@ func TestQueryCodeList(t *testing.T) { for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, nil) keeper := keepers.WasmKeeper for _, codeID := range spec.codeIDs { @@ -353,21 +333,20 @@ func TestQueryCodeList(t *testing.T) { wasmCode), ) } - q := NewQuerier(keeper) // when - query := []string{QueryListCode} - data := abci.RequestQuery{} - resData, err := q(ctx, query, data) + q := NewQuerier(keeper) + got, err := q.Codes(sdk.WrapSDKContext(ctx), nil) // then + if len(spec.codeIDs) == 0 { + require.Error(t, err) + return + } require.NoError(t, err) - var got []map[string]interface{} - err = json.Unmarshal(resData, &got) - require.NoError(t, err) - require.Len(t, got, len(spec.codeIDs)) + require.Len(t, got.CodeInfos, len(spec.codeIDs)) for i, exp := range spec.codeIDs { - assert.EqualValues(t, exp, got[i]["id"]) + assert.EqualValues(t, exp, got.CodeInfos[i].CodeID) } }) } diff --git a/x/wasm/internal/keeper/query_plugins.go b/x/wasm/internal/keeper/query_plugins.go index 862575f78f..20a97830cb 100644 --- a/x/wasm/internal/keeper/query_plugins.go +++ b/x/wasm/internal/keeper/query_plugins.go @@ -2,13 +2,15 @@ package keeper import ( "encoding/json" + wasmTypes "github.com/CosmWasm/go-cosmwasm/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/bank" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/staking" - abci "github.com/tendermint/tendermint/abci/types" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" ) type QueryHandler struct { @@ -57,7 +59,7 @@ type QueryPlugins struct { Wasm func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) } -func DefaultQueryPlugins(bank bank.ViewKeeper, staking staking.Keeper, distKeeper distribution.Keeper, wasm *Keeper) QueryPlugins { +func DefaultQueryPlugins(bank bankkeeper.ViewKeeper, staking stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, wasm *Keeper) QueryPlugins { return QueryPlugins{ Bank: BankQuerier(bank), Custom: NoCustomQuerier, @@ -86,14 +88,14 @@ func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins { return e } -func BankQuerier(bank bank.ViewKeeper) func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) { +func BankQuerier(bankKeeper bankkeeper.ViewKeeper) func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) { return func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) { if request.AllBalances != nil { addr, err := sdk.AccAddressFromBech32(request.AllBalances.Address) if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.AllBalances.Address) } - coins := bank.GetCoins(ctx, addr) + coins := bankKeeper.GetAllBalances(ctx, addr) res := wasmTypes.AllBalancesResponse{ Amount: convertSdkCoinsToWasmCoins(coins), } @@ -104,7 +106,7 @@ func BankQuerier(bank bank.ViewKeeper) func(ctx sdk.Context, request *wasmTypes. if err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Balance.Address) } - coins := bank.GetCoins(ctx, addr) + coins := bankKeeper.GetAllBalances(ctx, addr) amount := coins.AmountOf(request.Balance.Denom) res := wasmTypes.BalanceResponse{ Amount: wasmTypes.Coin{ @@ -122,7 +124,7 @@ func NoCustomQuerier(sdk.Context, json.RawMessage) ([]byte, error) { return nil, wasmTypes.UnsupportedRequest{Kind: "custom"} } -func StakingQuerier(keeper staking.Keeper, distKeeper distribution.Keeper) func(ctx sdk.Context, request *wasmTypes.StakingQuery) ([]byte, error) { +func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper) func(ctx sdk.Context, request *wasmTypes.StakingQuery) ([]byte, error) { return func(ctx sdk.Context, request *wasmTypes.StakingQuery) ([]byte, error) { if request.BondedDenom != nil { denom := keeper.BondDenom(ctx) @@ -137,7 +139,7 @@ func StakingQuerier(keeper staking.Keeper, distKeeper distribution.Keeper) func( wasmVals := make([]wasmTypes.Validator, len(validators)) for i, v := range validators { wasmVals[i] = wasmTypes.Validator{ - Address: v.OperatorAddress.String(), + Address: v.OperatorAddress, Commission: v.Commission.Rate.String(), MaxCommission: v.Commission.MaxRate.String(), MaxChangeRate: v.Commission.MaxChangeRate.String(), @@ -187,32 +189,49 @@ func StakingQuerier(keeper staking.Keeper, distKeeper distribution.Keeper) func( } } -func sdkToDelegations(ctx sdk.Context, keeper staking.Keeper, delegations []staking.Delegation) (wasmTypes.Delegations, error) { +func sdkToDelegations(ctx sdk.Context, keeper stakingkeeper.Keeper, delegations []stakingtypes.Delegation) (wasmTypes.Delegations, error) { result := make([]wasmTypes.Delegation, len(delegations)) bondDenom := keeper.BondDenom(ctx) for i, d := range delegations { + delAddr, err := sdk.AccAddressFromBech32(d.DelegatorAddress) + if err != nil { + return nil, sdkerrors.Wrap(err, "delegator address") + } + valAddr, err := sdk.ValAddressFromBech32(d.ValidatorAddress) + if err != nil { + return nil, sdkerrors.Wrap(err, "validator address") + } + // shares to amount logic comes from here: // https://github.com/cosmos/cosmos-sdk/blob/v0.38.3/x/staking/keeper/querier.go#L404 - val, found := keeper.GetValidator(ctx, d.ValidatorAddress) + val, found := keeper.GetValidator(ctx, valAddr) if !found { - return nil, sdkerrors.Wrap(staking.ErrNoValidatorFound, "can't load validator for delegation") + return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) result[i] = wasmTypes.Delegation{ - Delegator: d.DelegatorAddress.String(), - Validator: d.ValidatorAddress.String(), + Delegator: delAddr.String(), + Validator: valAddr.String(), Amount: convertSdkCoinToWasmCoin(amount), } } return result, nil } -func sdkToFullDelegation(ctx sdk.Context, keeper staking.Keeper, distKeeper distribution.Keeper, delegation staking.Delegation) (*wasmTypes.FullDelegation, error) { - val, found := keeper.GetValidator(ctx, delegation.ValidatorAddress) +func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) (*wasmTypes.FullDelegation, error) { + delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) + if err != nil { + return nil, sdkerrors.Wrap(err, "delegator address") + } + valAddr, err := sdk.ValAddressFromBech32(delegation.ValidatorAddress) + if err != nil { + return nil, sdkerrors.Wrap(err, "validator address") + } + val, found := keeper.GetValidator(ctx, valAddr) if !found { - return nil, sdkerrors.Wrap(staking.ErrNoValidatorFound, "can't load validator for delegation") + return nil, sdkerrors.Wrap(stakingtypes.ErrNoValidatorFound, "can't load validator for delegation") } bondDenom := keeper.BondDenom(ctx) amount := sdk.NewCoin(bondDenom, val.TokensFromShares(delegation.Shares).TruncateInt()) @@ -225,7 +244,7 @@ func sdkToFullDelegation(ctx sdk.Context, keeper staking.Keeper, distKeeper dist // otherwise, it can redelegate the full amount // (there are cases of partial funds redelegated, but this is a start) redelegateCoins := wasmTypes.NewCoin(0, bondDenom) - if !keeper.HasReceivingRedelegation(ctx, delegation.DelegatorAddress, delegation.ValidatorAddress) { + if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { redelegateCoins = delegationCoins } @@ -239,8 +258,8 @@ func sdkToFullDelegation(ctx sdk.Context, keeper staking.Keeper, distKeeper dist } return &wasmTypes.FullDelegation{ - Delegator: delegation.DelegatorAddress.String(), - Validator: delegation.ValidatorAddress.String(), + Delegator: delAddr.String(), + Validator: valAddr.String(), Amount: delegationCoins, AccumulatedRewards: accRewards, CanRedelegate: redelegateCoins, @@ -249,35 +268,21 @@ func sdkToFullDelegation(ctx sdk.Context, keeper staking.Keeper, distKeeper dist // FIXME: simplify this enormously when // https://github.com/cosmos/cosmos-sdk/issues/7466 is merged -func getAccumulatedRewards(ctx sdk.Context, distKeeper distribution.Keeper, delegation staking.Delegation) ([]wasmTypes.Coin, error) { +func getAccumulatedRewards(ctx sdk.Context, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) ([]wasmTypes.Coin, error) { // Try to get *delegator* reward info! - params := distribution.QueryDelegationRewardsParams{ + params := distributiontypes.QueryDelegationRewardsRequest{ DelegatorAddress: delegation.DelegatorAddress, ValidatorAddress: delegation.ValidatorAddress, } - data, err := json.Marshal(params) - if err != nil { - return nil, err - } - req := abci.RequestQuery{Data: data} - - // just to be safe... ensure we do not accidentally write in the querier (which does some funky things) cache, _ := ctx.CacheContext() - qres, err := distribution.NewQuerier(distKeeper)(cache, []string{distribution.QueryDelegationRewards}, req) - if err != nil { - return nil, err - } - - var decRewards sdk.DecCoins - err = json.Unmarshal(qres, &decRewards) + qres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), ¶ms) if err != nil { return nil, err } - // **** all this above should be ONE method call // now we have it, convert it into wasmTypes - rewards := make([]wasmTypes.Coin, len(decRewards)) - for i, r := range decRewards { + rewards := make([]wasmTypes.Coin, len(qres.Rewards)) + for i, r := range qres.Rewards { rewards[i] = wasmTypes.Coin{ Denom: r.Denom, Amount: r.Amount.TruncateInt().String(), diff --git a/x/wasm/internal/keeper/recurse_test.go b/x/wasm/internal/keeper/recurse_test.go index 4a9bf1454c..4d91b8daa5 100644 --- a/x/wasm/internal/keeper/recurse_test.go +++ b/x/wasm/internal/keeper/recurse_test.go @@ -2,8 +2,6 @@ package keeper import ( "encoding/json" - "io/ioutil" - "os" "testing" wasmTypes "github.com/CosmWasm/go-cosmwasm/types" @@ -38,12 +36,8 @@ type recurseResponse struct { // number os wasm queries called from a contract var totalWasmQueryCounter int -func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.AccAddress, ctx sdk.Context, keeper Keeper, cleanup func()) { +func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.AccAddress, ctx sdk.Context, keeper Keeper) { // we do one basic setup before all test cases (which are read-only and don't change state) - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - cleanup = func() { os.RemoveAll(tempDir) } - var realWasmQuerier func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) countingQuerier := &QueryPlugins{ Wasm: func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) { @@ -51,39 +45,20 @@ func initRecurseContract(t *testing.T) (contract sdk.AccAddress, creator sdk.Acc return realWasmQuerier(ctx, request) }, } - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, countingQuerier) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper - realWasmQuerier = WasmQuerier(&keeper) - deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator = createFakeFundedAccount(ctx, accKeeper, deposit.Add(deposit...)) - - // store the code - wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") - require.NoError(t, err) - codeID, err := keeper.Create(ctx, creator, wasmCode, "", "", nil) - require.NoError(t, err) - - // instantiate the contract - _, _, bob := keyPubAddr() - _, _, fred := keyPubAddr() - initMsg := InitMsg{ - Verifier: fred, - Beneficiary: bob, - } - initMsgBz, err := json.Marshal(initMsg) - require.NoError(t, err) - contractAddr, err := keeper.Instantiate(ctx, codeID, creator, nil, initMsgBz, "recursive contract", deposit) - require.NoError(t, err) + ctx, keepers := CreateTestInput(t, false, SupportedFeatures, nil, countingQuerier) + keeper = keepers.WasmKeeper + realWasmQuerier = WasmQuerier(&keeper) - return contractAddr, creator, ctx, keeper, cleanup + exampleContract := InstantiateHackatomExampleContract(t, ctx, keepers) + return exampleContract.Contract, exampleContract.CreatorAddr, ctx, keeper } func TestGasCostOnQuery(t *testing.T) { const ( - GasNoWork uint64 = InstanceCost + 2_953 + GasNoWork uint64 = InstanceCost + 2_938 // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork50 uint64 = InstanceCost + 8_661 // this is a little shy of 50k gas - to keep an eye on the limit + GasWork50 uint64 = 48646 // this is a little shy of 50k gas - to keep an eye on the limit GasReturnUnhashed uint64 = 393 GasReturnHashed uint64 = 342 @@ -132,8 +107,7 @@ func TestGasCostOnQuery(t *testing.T) { }, } - contractAddr, creator, ctx, keeper, cleanup := initRecurseContract(t) - defer cleanup() + contractAddr, creator, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { @@ -209,8 +183,7 @@ func TestGasOnExternalQuery(t *testing.T) { }, } - contractAddr, _, ctx, keeper, cleanup := initRecurseContract(t) - defer cleanup() + contractAddr, _, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { @@ -227,12 +200,12 @@ func TestGasOnExternalQuery(t *testing.T) { if tc.expectPanic { require.Panics(t, func() { // this should run out of gas - _, err := NewQuerier(keeper)(ctx, path, req) + _, err := NewLegacyQuerier(keeper)(ctx, path, req) t.Logf("%v", err) }) } else { // otherwise, make sure we get a good success - _, err := NewQuerier(keeper)(ctx, path, req) + _, err := NewLegacyQuerier(keeper)(ctx, path, req) require.NoError(t, err) } }) @@ -249,7 +222,7 @@ func TestLimitRecursiveQueryGas(t *testing.T) { const ( // Note: about 100 SDK gas (10k wasmer gas) for each round of sha256 - GasWork2k uint64 = InstanceCost + 233_575 // we have 6x gas used in cpu than in the instance + GasWork2k uint64 = 273_560 // = InstanceCost + x // we have 6x gas used in cpu than in the instance // This is overhead for calling into a sub-contract GasReturnHashed uint64 = 349 ) @@ -277,7 +250,7 @@ func TestLimitRecursiveQueryGas(t *testing.T) { Work: 2000, }, expectQueriesFromContract: 5, - // FIXME: why -3... confused a bit by calculations, seems like rounding issues + // FIXME: why -2... confused a bit by calculations, seems like rounding issues expectedGas: GasWork2k + 5*(GasWork2k+GasReturnHashed) - 2, }, // this is where we expect an error... @@ -295,8 +268,7 @@ func TestLimitRecursiveQueryGas(t *testing.T) { }, } - contractAddr, _, ctx, keeper, cleanup := initRecurseContract(t) - defer cleanup() + contractAddr, _, ctx, keeper := initRecurseContract(t) for name, tc := range cases { t.Run(name, func(t *testing.T) { diff --git a/x/wasm/internal/keeper/reflect_test.go b/x/wasm/internal/keeper/reflect_test.go index 88ff938ff4..6c5542a934 100644 --- a/x/wasm/internal/keeper/reflect_test.go +++ b/x/wasm/internal/keeper/reflect_test.go @@ -3,20 +3,20 @@ package keeper import ( "encoding/json" "io/ioutil" - "os" "strings" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" "github.com/cosmos/cosmos-sdk/codec" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/bank" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // MaskInitMsg is {} @@ -72,14 +72,12 @@ func mustParse(t *testing.T, data []byte, res interface{}) { const MaskFeatures = "staking,mask" func TestMaskReflectContractSend(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, MaskFeatures, maskEncoders(MakeTestCodec()), nil) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + cdc := MakeTestCodec() + ctx, keepers := CreateTestInput(t, false, MaskFeatures, maskEncoders(cdc), nil) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) _, _, bob := keyPubAddr() // upload mask code @@ -103,7 +101,7 @@ func TestMaskReflectContractSend(t *testing.T) { require.NotEmpty(t, maskAddr) // now we set contract as verifier of an escrow - initMsg := InitMsg{ + initMsg := HackatomExampleInitMsg{ Verifier: maskAddr, Beneficiary: bob, } @@ -115,10 +113,10 @@ func TestMaskReflectContractSend(t *testing.T) { require.NotEmpty(t, escrowAddr) // let's make sure all balances make sense - checkAccount(t, ctx, accKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // 100k - 40k - 25k - checkAccount(t, ctx, accKeeper, maskAddr, maskStart) - checkAccount(t, ctx, accKeeper, escrowAddr, escrowStart) - checkAccount(t, ctx, accKeeper, bob, nil) + checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // 100k - 40k - 25k + checkAccount(t, ctx, accKeeper, bankKeeper, maskAddr, maskStart) + checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, escrowStart) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, nil) // now for the trick.... we reflect a message through the mask to call the escrow // we also send an additional 14k tokens there. @@ -148,23 +146,21 @@ func TestMaskReflectContractSend(t *testing.T) { require.NoError(t, err) // did this work??? - checkAccount(t, ctx, accKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // same as before - checkAccount(t, ctx, accKeeper, maskAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) - checkAccount(t, ctx, accKeeper, escrowAddr, sdk.Coins{}) // emptied reserved - checkAccount(t, ctx, accKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k + checkAccount(t, ctx, accKeeper, bankKeeper, creator, sdk.NewCoins(sdk.NewInt64Coin("denom", 35000))) // same as before + checkAccount(t, ctx, accKeeper, bankKeeper, maskAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 26000))) // 40k - 14k (from send) + checkAccount(t, ctx, accKeeper, bankKeeper, escrowAddr, sdk.Coins{}) // emptied reserved + checkAccount(t, ctx, accKeeper, bankKeeper, bob, sdk.NewCoins(sdk.NewInt64Coin("denom", 39000))) // all escrow of 25k + 14k } func TestMaskReflectCustomMsg(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, MaskFeatures, maskEncoders(MakeTestCodec()), maskPlugins()) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + cdc := MakeTestCodec() + ctx, keepers := CreateTestInput(t, false, MaskFeatures, maskEncoders(cdc), maskPlugins()) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) - bob := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) + bob := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) _, _, fred := keyPubAddr() // upload code @@ -192,9 +188,9 @@ func TestMaskReflectCustomMsg(t *testing.T) { require.NoError(t, err) // check some account values - checkAccount(t, ctx, accKeeper, contractAddr, contractStart) - checkAccount(t, ctx, accKeeper, bob, deposit) - checkAccount(t, ctx, accKeeper, fred, nil) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, contractStart) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) + checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) // bob can send contract's tokens to fred (using SendMsg) msgs := []wasmTypes.CosmosMsg{{ @@ -220,18 +216,18 @@ func TestMaskReflectCustomMsg(t *testing.T) { require.NoError(t, err) // fred got coins - checkAccount(t, ctx, accKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) + checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 15000))) // contract lost them - checkAccount(t, ctx, accKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) - checkAccount(t, ctx, accKeeper, bob, deposit) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 25000))) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) // construct an opaque message - var sdkSendMsg sdk.Msg = &bank.MsgSend{ - FromAddress: contractAddr, - ToAddress: fred, + var sdkSendMsg sdk.Msg = &banktypes.MsgSend{ + FromAddress: contractAddr.String(), + ToAddress: fred.String(), Amount: sdk.NewCoins(sdk.NewInt64Coin("denom", 23000)), } - opaque, err := toMaskRawMsg(keeper.cdc, sdkSendMsg) + opaque, err := toMaskRawMsg(cdc, sdkSendMsg) require.NoError(t, err) reflectOpaque := MaskHandleMsg{ Reflect: &reflectPayload{ @@ -245,21 +241,19 @@ func TestMaskReflectCustomMsg(t *testing.T) { require.NoError(t, err) // fred got more coins - checkAccount(t, ctx, accKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 38000))) + checkAccount(t, ctx, accKeeper, bankKeeper, fred, sdk.NewCoins(sdk.NewInt64Coin("denom", 38000))) // contract lost them - checkAccount(t, ctx, accKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 2000))) - checkAccount(t, ctx, accKeeper, bob, deposit) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.NewCoins(sdk.NewInt64Coin("denom", 2000))) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, deposit) } func TestMaskReflectCustomQuery(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, MaskFeatures, maskEncoders(MakeTestCodec()), maskPlugins()) - accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper + cdc := MakeTestCodec() + ctx, keepers := CreateTestInput(t, false, MaskFeatures, maskEncoders(cdc), maskPlugins()) + accKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) // upload code maskCode, err := ioutil.ReadFile("./testdata/reflect.wasm") @@ -308,14 +302,11 @@ type maskState struct { } func TestMaskReflectWasmQueries(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, MaskFeatures, maskEncoders(MakeTestCodec()), nil) + ctx, keepers := CreateTestInput(t, false, MaskFeatures, maskEncoders(MakeTestCodec()), nil) accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, keepers.BankKeeper, deposit) // upload mask code maskCode, err := ioutil.ReadFile("./testdata/reflect.wasm") @@ -382,14 +373,11 @@ func TestMaskReflectWasmQueries(t *testing.T) { } func TestWasmRawQueryWithNil(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, MaskFeatures, maskEncoders(MakeTestCodec()), nil) + ctx, keepers := CreateTestInput(t, false, MaskFeatures, maskEncoders(MakeTestCodec()), nil) accKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, keepers.BankKeeper, deposit) // upload mask code maskCode, err := ioutil.ReadFile("./testdata/reflect.wasm") @@ -429,7 +417,7 @@ func TestWasmRawQueryWithNil(t *testing.T) { require.Equal(t, []byte{}, reflectRawRes.Data) } -func checkAccount(t *testing.T, ctx sdk.Context, accKeeper auth.AccountKeeper, addr sdk.AccAddress, expected sdk.Coins) { +func checkAccount(t *testing.T, ctx sdk.Context, accKeeper authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, addr sdk.AccAddress, expected sdk.Coins) { acct := accKeeper.GetAccount(ctx, addr) if expected == nil { assert.Nil(t, acct) @@ -437,9 +425,9 @@ func checkAccount(t *testing.T, ctx sdk.Context, accKeeper auth.AccountKeeper, a assert.NotNil(t, acct) if expected.Empty() { // there is confusion between nil and empty slice... let's just treat them the same - assert.True(t, acct.GetCoins().Empty()) + assert.True(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()).Empty()) } else { - assert.Equal(t, acct.GetCoins(), expected) + assert.Equal(t, bankKeeper.GetAllBalances(ctx, acct.GetAddress()), expected) } } } @@ -451,10 +439,14 @@ type maskCustomMsg struct { Raw []byte `json:"raw,omitempty"` } -// toMaskRawMsg encodes an sdk msg using amino json encoding. +// toMaskRawMsg encodes an sdk msg using any type with json encoding. // Then wraps it as an opaque message -func toMaskRawMsg(cdc *codec.Codec, msg sdk.Msg) (wasmTypes.CosmosMsg, error) { - rawBz, err := cdc.MarshalJSON(msg) +func toMaskRawMsg(cdc codec.Marshaler, msg sdk.Msg) (wasmTypes.CosmosMsg, error) { + any, err := codectypes.NewAnyWithValue(msg) + if err != nil { + return wasmTypes.CosmosMsg{}, err + } + rawBz, err := cdc.MarshalJSON(any) if err != nil { return wasmTypes.CosmosMsg{}, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } @@ -468,15 +460,15 @@ func toMaskRawMsg(cdc *codec.Codec, msg sdk.Msg) (wasmTypes.CosmosMsg, error) { } // maskEncoders needs to be registered in test setup to handle custom message callbacks -func maskEncoders(cdc *codec.Codec) *MessageEncoders { +func maskEncoders(cdc codec.Marshaler) *MessageEncoders { return &MessageEncoders{ Custom: fromMaskRawMsg(cdc), } } -// fromMaskRawMsg decodes msg.Data to an sdk.Msg using amino json encoding. +// fromMaskRawMsg decodes msg.Data to an sdk.Msg using proto Any and json encoding. // this needs to be registered on the Encoders -func fromMaskRawMsg(cdc *codec.Codec) CustomEncoder { +func fromMaskRawMsg(cdc codec.Marshaler) CustomEncoder { return func(_sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) { var custom maskCustomMsg err := json.Unmarshal(msg, &custom) @@ -484,12 +476,15 @@ func fromMaskRawMsg(cdc *codec.Codec) CustomEncoder { return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } if custom.Raw != nil { - var sdkMsg sdk.Msg - err := cdc.UnmarshalJSON(custom.Raw, &sdkMsg) - if err != nil { + var any codectypes.Any + if err := cdc.UnmarshalJSON(custom.Raw, &any); err != nil { return nil, sdkerrors.Wrap(sdkerrors.ErrJSONUnmarshal, err.Error()) } - return []sdk.Msg{sdkMsg}, nil + var msg sdk.Msg + if err := cdc.UnpackAny(&any, &msg); err != nil { + return nil, err + } + return []sdk.Msg{msg}, nil } if custom.Debug != "" { return nil, sdkerrors.Wrapf(types.ErrInvalidMsg, "Custom Debug: %s", custom.Debug) diff --git a/x/wasm/internal/keeper/staking_test.go b/x/wasm/internal/keeper/staking_test.go index 7e66405d66..75e1537377 100644 --- a/x/wasm/internal/keeper/staking_test.go +++ b/x/wasm/internal/keeper/staking_test.go @@ -2,19 +2,21 @@ package keeper import ( "encoding/json" + "io/ioutil" + "testing" + wasmTypes "github.com/CosmWasm/go-cosmwasm/types" - "github.com/cosmos/cosmos-sdk/x/auth" - "github.com/cosmos/cosmos-sdk/x/distribution" + sdk "github.com/cosmos/cosmos-sdk/types" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" "github.com/cosmos/cosmos-sdk/x/staking" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" "github.com/cosmos/cosmos-sdk/x/staking/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" "github.com/stretchr/testify/assert" - "io/ioutil" - "os" - "testing" - "github.com/stretchr/testify/require" - - sdk "github.com/cosmos/cosmos-sdk/types" ) type StakingInitMsg struct { @@ -86,20 +88,17 @@ type InvestmentResponse struct { } func TestInitializeStaking(t *testing.T) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - defer os.RemoveAll(tempDir) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, stakingKeeper, keeper := keepers.AccountKeeper, keepers.StakingKeeper, keepers.WasmKeeper + ctx, k := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.WasmKeeper, k.BankKeeper - valAddr := addValidator(ctx, stakingKeeper, accKeeper, sdk.NewInt64Coin("stake", 1234567)) + valAddr := addValidator(t, ctx, stakingKeeper, accKeeper, bankKeeper, sdk.NewInt64Coin("stake", 1234567)) ctx = nextBlock(ctx, stakingKeeper) v, found := stakingKeeper.GetValidator(ctx, valAddr) assert.True(t, found) assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1234567)) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) // upload staking derivates code stakingCode, err := ioutil.ReadFile("./testdata/staking.wasm") @@ -125,7 +124,7 @@ func TestInitializeStaking(t *testing.T) { require.NotEmpty(t, stakingAddr) // nothing spent here - checkAccount(t, ctx, accKeeper, creator, deposit) + checkAccount(t, ctx, accKeeper, bankKeeper, creator, deposit) // try to register with a validator not on the list and it fails _, _, bob := keyPubAddr() @@ -154,25 +153,22 @@ type initInfo struct { contractAddr sdk.AccAddress ctx sdk.Context - accKeeper auth.AccountKeeper - stakingKeeper staking.Keeper - distKeeper distribution.Keeper + accKeeper authkeeper.AccountKeeper + stakingKeeper stakingkeeper.Keeper + distKeeper distributionkeeper.Keeper wasmKeeper Keeper - - cleanup func() + bankKeeper bankkeeper.Keeper } func initializeStaking(t *testing.T) initInfo { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - ctx, keepers := CreateTestInput(t, false, tempDir, SupportedFeatures, nil, nil) - accKeeper, stakingKeeper, keeper := keepers.AccountKeeper, keepers.StakingKeeper, keepers.WasmKeeper + ctx, k := CreateTestInput(t, false, SupportedFeatures, nil, nil) + accKeeper, stakingKeeper, keeper, bankKeeper := k.AccountKeeper, k.StakingKeeper, k.WasmKeeper, k.BankKeeper - valAddr := addValidator(ctx, stakingKeeper, accKeeper, sdk.NewInt64Coin("stake", 1000000)) + valAddr := addValidator(t, ctx, stakingKeeper, accKeeper, bankKeeper, sdk.NewInt64Coin("stake", 1000000)) ctx = nextBlock(ctx, stakingKeeper) // set some baseline - this seems to be needed - keepers.DistKeeper.SetValidatorHistoricalRewards(ctx, valAddr, 0, distribution.ValidatorHistoricalRewards{ + k.DistKeeper.SetValidatorHistoricalRewards(ctx, valAddr, 0, distributiontypes.ValidatorHistoricalRewards{ CumulativeRewardRatio: sdk.DecCoins{}, ReferenceCount: 1, }) @@ -180,10 +176,10 @@ func initializeStaking(t *testing.T) initInfo { v, found := stakingKeeper.GetValidator(ctx, valAddr) assert.True(t, found) assert.Equal(t, v.GetDelegatorShares(), sdk.NewDec(1000000)) - assert.Equal(t, v.Status, sdk.Bonded) + assert.Equal(t, v.Status, stakingtypes.Bonded) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000), sdk.NewInt64Coin("stake", 500000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, deposit) // upload staking derivates code stakingCode, err := ioutil.ReadFile("./testdata/staking.wasm") @@ -216,16 +212,15 @@ func initializeStaking(t *testing.T) initInfo { accKeeper: accKeeper, stakingKeeper: stakingKeeper, wasmKeeper: keeper, - distKeeper: keepers.DistKeeper, - cleanup: func() { os.RemoveAll(tempDir) }, + distKeeper: k.DistKeeper, + bankKeeper: bankKeeper, } } func TestBonding(t *testing.T) { initInfo := initializeStaking(t) - defer initInfo.cleanup() ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper + keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper // initial checks of bonding state val, found := stakingKeeper.GetValidator(ctx, valAddr) @@ -235,7 +230,7 @@ func TestBonding(t *testing.T) { // bob has 160k, putting 80k into the contract full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := createFakeFundedAccount(ctx, accKeeper, full) + bob := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, full) // check contract state before assertBalance(t, ctx, keeper, contractAddr, bob, "0") @@ -251,8 +246,8 @@ func TestBonding(t *testing.T) { require.NoError(t, err) // check some account values - the money is on neither account (cuz it is bonded) - checkAccount(t, ctx, accKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bob, funds) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) // make sure the proper number of tokens have been bonded val, _ = stakingKeeper.GetValidator(ctx, valAddr) @@ -272,9 +267,8 @@ func TestBonding(t *testing.T) { func TestUnbonding(t *testing.T) { initInfo := initializeStaking(t) - defer initInfo.cleanup() ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper + keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper // initial checks of bonding state val, found := stakingKeeper.GetValidator(ctx, valAddr) @@ -284,7 +278,7 @@ func TestUnbonding(t *testing.T) { // bob has 160k, putting 80k into the contract full := sdk.NewCoins(sdk.NewInt64Coin("stake", 160000)) funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 80000)) - bob := createFakeFundedAccount(ctx, accKeeper, full) + bob := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, full) bond := StakingHandleMsg{ Bond: &struct{}{}, @@ -310,8 +304,8 @@ func TestUnbonding(t *testing.T) { // check some account values - the money is on neither account (cuz it is bonded) // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bob, funds) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) // make sure the proper number of tokens have been bonded (80k - 27k = 53k) val, _ = stakingKeeper.GetValidator(ctx, valAddr) @@ -338,9 +332,8 @@ func TestUnbonding(t *testing.T) { func TestReinvest(t *testing.T) { initInfo := initializeStaking(t) - defer initInfo.cleanup() ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr - keeper, stakingKeeper, accKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper + keeper, stakingKeeper, accKeeper, bankKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper, initInfo.bankKeeper distKeeper := initInfo.distKeeper // initial checks of bonding state @@ -352,7 +345,7 @@ func TestReinvest(t *testing.T) { // full is 2x funds, 1x goes to the contract, other stays on his wallet full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := createFakeFundedAccount(ctx, accKeeper, full) + bob := createFakeFundedAccount(t, ctx, accKeeper, bankKeeper, full) // we will stake 200k to a validator with 1M self-bond // this means we should get 1/6 of the rewards @@ -380,8 +373,8 @@ func TestReinvest(t *testing.T) { // check some account values - the money is on neither account (cuz it is bonded) // Note: why is this immediate? just test setup? - checkAccount(t, ctx, accKeeper, contractAddr, sdk.Coins{}) - checkAccount(t, ctx, accKeeper, bob, funds) + checkAccount(t, ctx, accKeeper, bankKeeper, contractAddr, sdk.Coins{}) + checkAccount(t, ctx, accKeeper, bankKeeper, bob, funds) // check the delegation itself d, found := stakingKeeper.GetDelegation(ctx, contractAddr, valAddr) @@ -408,7 +401,6 @@ func TestReinvest(t *testing.T) { func TestQueryStakingInfo(t *testing.T) { // STEP 1: take a lot of setup from TestReinvest so we have non-zero info initInfo := initializeStaking(t) - defer initInfo.cleanup() ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr keeper, stakingKeeper, accKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper distKeeper := initInfo.distKeeper @@ -421,7 +413,7 @@ func TestQueryStakingInfo(t *testing.T) { // full is 2x funds, 1x goes to the contract, other stays on his wallet full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := createFakeFundedAccount(ctx, accKeeper, full) + bob := createFakeFundedAccount(t, ctx, accKeeper, initInfo.bankKeeper, full) // we will stake 200k to a validator with 1M self-bond // this means we should get 1/6 of the rewards @@ -443,7 +435,7 @@ func TestQueryStakingInfo(t *testing.T) { // STEP 2: Prepare the mask contract deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(ctx, accKeeper, deposit) + creator := createFakeFundedAccount(t, ctx, accKeeper, initInfo.bankKeeper, deposit) // upload mask code maskCode, err := ioutil.ReadFile("./testdata/reflect.wasm") @@ -551,7 +543,6 @@ func TestQueryStakingInfo(t *testing.T) { func TestQueryStakingPlugin(t *testing.T) { // STEP 1: take a lot of setup from TestReinvest so we have non-zero info initInfo := initializeStaking(t) - defer initInfo.cleanup() ctx, valAddr, contractAddr := initInfo.ctx, initInfo.valAddr, initInfo.contractAddr keeper, stakingKeeper, accKeeper := initInfo.wasmKeeper, initInfo.stakingKeeper, initInfo.accKeeper distKeeper := initInfo.distKeeper @@ -564,7 +555,7 @@ func TestQueryStakingPlugin(t *testing.T) { // full is 2x funds, 1x goes to the contract, other stays on his wallet full := sdk.NewCoins(sdk.NewInt64Coin("stake", 400000)) funds := sdk.NewCoins(sdk.NewInt64Coin("stake", 200000)) - bob := createFakeFundedAccount(ctx, accKeeper, full) + bob := createFakeFundedAccount(t, ctx, accKeeper, initInfo.bankKeeper, full) // we will stake 200k to a validator with 1M self-bond // this means we should get 1/6 of the rewards @@ -616,14 +607,14 @@ func TestQueryStakingPlugin(t *testing.T) { } // adds a few validators and returns a list of validators that are registered -func addValidator(ctx sdk.Context, stakingKeeper staking.Keeper, accountKeeper auth.AccountKeeper, value sdk.Coin) sdk.ValAddress { +func addValidator(t *testing.T, ctx sdk.Context, stakingKeeper stakingkeeper.Keeper, accountKeeper authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, value sdk.Coin) sdk.ValAddress { _, pub, accAddr := keyPubAddr() addr := sdk.ValAddress(accAddr) - owner := createFakeFundedAccount(ctx, accountKeeper, sdk.Coins{value}) + owner := createFakeFundedAccount(t, ctx, accountKeeper, bankKeeper, sdk.Coins{value}) - msg := staking.MsgCreateValidator{ + msg := stakingtypes.MsgCreateValidator{ Description: types.Description{ Moniker: "Validator power", }, @@ -633,30 +624,28 @@ func addValidator(ctx sdk.Context, stakingKeeper staking.Keeper, accountKeeper a MaxChangeRate: sdk.MustNewDecFromStr("0.01"), }, MinSelfDelegation: sdk.OneInt(), - DelegatorAddress: owner, - ValidatorAddress: addr, - PubKey: pub, + DelegatorAddress: owner.String(), + ValidatorAddress: addr.String(), + Pubkey: sdk.MustBech32ifyPubKey(sdk.Bech32PubKeyTypeConsPub, pub), Value: value, } h := staking.NewHandler(stakingKeeper) - _, err := h(ctx, msg) - if err != nil { - panic(err) - } + _, err := h(ctx, &msg) + require.NoError(t, err) return addr } // this will commit the current set, update the block height and set historic info // basically, letting two blocks pass -func nextBlock(ctx sdk.Context, stakingKeeper staking.Keeper) sdk.Context { +func nextBlock(ctx sdk.Context, stakingKeeper stakingkeeper.Keeper) sdk.Context { staking.EndBlocker(ctx, stakingKeeper) ctx = ctx.WithBlockHeight(ctx.BlockHeight() + 1) staking.BeginBlocker(ctx, stakingKeeper) return ctx } -func setValidatorRewards(ctx sdk.Context, stakingKeeper staking.Keeper, distKeeper distribution.Keeper, valAddr sdk.ValAddress, reward string) { +func setValidatorRewards(ctx sdk.Context, stakingKeeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, valAddr sdk.ValAddress, reward string) { // allocate some rewards vali := stakingKeeper.Validator(ctx, valAddr) amount, err := sdk.NewDecFromStr(reward) diff --git a/x/wasm/internal/keeper/test_common.go b/x/wasm/internal/keeper/test_common.go index 4c12259555..06a9b6cbf2 100644 --- a/x/wasm/internal/keeper/test_common.go +++ b/x/wasm/internal/keeper/test_common.go @@ -1,56 +1,110 @@ package keeper import ( + "encoding/binary" + "encoding/json" "fmt" + "io/ioutil" + "os" "testing" "time" - "github.com/cosmos/cosmos-sdk/x/distribution" - "github.com/cosmos/cosmos-sdk/x/gov" - govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" - - "github.com/stretchr/testify/require" - abci "github.com/tendermint/tendermint/abci/types" - "github.com/tendermint/tendermint/libs/log" - dbm "github.com/tendermint/tm-db" - + wasmTypes "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmtypes "github.com/CosmWasm/wasmd/x/wasm/internal/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + params2 "github.com/cosmos/cosmos-sdk/simapp/params" + "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/store" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/cosmos/cosmos-sdk/types/module" "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + "github.com/cosmos/cosmos-sdk/x/auth/tx" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" "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" + "github.com/cosmos/cosmos-sdk/x/capability" + "github.com/cosmos/cosmos-sdk/x/crisis" + crisistypes "github.com/cosmos/cosmos-sdk/x/crisis/types" + "github.com/cosmos/cosmos-sdk/x/distribution" + distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client" + distributionkeeper "github.com/cosmos/cosmos-sdk/x/distribution/keeper" + distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" + "github.com/cosmos/cosmos-sdk/x/evidence" + "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" + ibctransfertypes "github.com/cosmos/cosmos-sdk/x/ibc/applications/transfer/types" + ibc "github.com/cosmos/cosmos-sdk/x/ibc/core" + "github.com/cosmos/cosmos-sdk/x/mint" + minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/cosmos/cosmos-sdk/x/params" + paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" + paramskeeper "github.com/cosmos/cosmos-sdk/x/params/keeper" + paramstypes "github.com/cosmos/cosmos-sdk/x/params/types" + paramproposal "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + "github.com/cosmos/cosmos-sdk/x/slashing" + slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" "github.com/cosmos/cosmos-sdk/x/staking" - "github.com/cosmos/cosmos-sdk/x/supply" + stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + "github.com/cosmos/cosmos-sdk/x/upgrade" + upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client" + "github.com/stretchr/testify/require" + "github.com/tendermint/tendermint/crypto" + "github.com/tendermint/tendermint/crypto/ed25519" + "github.com/tendermint/tendermint/libs/log" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + dbm "github.com/tendermint/tm-db" +) - wasmtypes "github.com/CosmWasm/wasmd/x/wasm/internal/types" +var ModuleBasics = module.NewBasicManager( + auth.AppModuleBasic{}, + bank.AppModuleBasic{}, + capability.AppModuleBasic{}, + staking.AppModuleBasic{}, + mint.AppModuleBasic{}, + distribution.AppModuleBasic{}, + gov.NewAppModuleBasic( + paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, + ), + params.AppModuleBasic{}, + crisis.AppModuleBasic{}, + slashing.AppModuleBasic{}, + ibc.AppModuleBasic{}, + upgrade.AppModuleBasic{}, + evidence.AppModuleBasic{}, + transfer.AppModuleBasic{}, ) -const flagLRUCacheSize = "lru_size" -const flagQueryGasLimit = "query_gas_limit" - -func MakeTestCodec() *codec.Codec { - var cdc = codec.New() - - // Register AppAccount - // cdc.RegisterInterface((*authexported.Account)(nil), nil) - // cdc.RegisterConcrete(&auth.BaseAccount{}, "test/wasm/BaseAccount", nil) - auth.AppModuleBasic{}.RegisterCodec(cdc) - bank.AppModuleBasic{}.RegisterCodec(cdc) - supply.AppModuleBasic{}.RegisterCodec(cdc) - staking.AppModuleBasic{}.RegisterCodec(cdc) - distribution.AppModuleBasic{}.RegisterCodec(cdc) - gov.RegisterCodec(cdc) - wasmtypes.RegisterCodec(cdc) - sdk.RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - params.RegisterCodec(cdc) - return cdc +func MakeTestCodec() codec.Marshaler { + return MakeEncodingConfig().Marshaler +} +func MakeEncodingConfig() params2.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 params2.EncodingConfig{ + InterfaceRegistry: interfaceRegistry, + Marshaler: marshaler, + TxConfig: txCfg, + Amino: amino, + } } -var TestingStakeParams = staking.Params{ +var TestingStakeParams = stakingtypes.Params{ UnbondingTime: 100, MaxValidators: 10, MaxEntries: 10, @@ -59,132 +113,149 @@ var TestingStakeParams = staking.Params{ } type TestKeepers struct { - AccountKeeper auth.AccountKeeper - StakingKeeper staking.Keeper + AccountKeeper authkeeper.AccountKeeper + StakingKeeper stakingkeeper.Keeper WasmKeeper Keeper - DistKeeper distribution.Keeper - SupplyKeeper supply.Keeper - GovKeeper gov.Keeper - BankKeeper bank.Keeper + DistKeeper distributionkeeper.Keeper + BankKeeper bankkeeper.Keeper + GovKeeper govkeeper.Keeper } // encoders can be nil to accept the defaults, or set it to override some of the message handlers (like default) -func CreateTestInput(t *testing.T, isCheckTx bool, tempDir string, supportedFeatures string, encoders *MessageEncoders, queriers *QueryPlugins) (sdk.Context, TestKeepers) { - keyContract := sdk.NewKVStoreKey(wasmtypes.StoreKey) - keyAcc := sdk.NewKVStoreKey(auth.StoreKey) - keyStaking := sdk.NewKVStoreKey(staking.StoreKey) - keySupply := sdk.NewKVStoreKey(supply.StoreKey) - keyDistro := sdk.NewKVStoreKey(distribution.StoreKey) - keyParams := sdk.NewKVStoreKey(params.StoreKey) - tkeyParams := sdk.NewTransientStoreKey(params.TStoreKey) +func CreateTestInput(t *testing.T, isCheckTx bool, supportedFeatures string, encoders *MessageEncoders, queriers *QueryPlugins) (sdk.Context, TestKeepers) { + tempDir, err := ioutil.TempDir("", "wasm") + require.NoError(t, err) + t.Cleanup(func() { os.RemoveAll(tempDir) }) + + keyWasm := sdk.NewKVStoreKey(wasmTypes.StoreKey) + keyAcc := sdk.NewKVStoreKey(authtypes.StoreKey) + keyBank := sdk.NewKVStoreKey(banktypes.StoreKey) + keyStaking := sdk.NewKVStoreKey(stakingtypes.StoreKey) + keyDistro := sdk.NewKVStoreKey(distributiontypes.StoreKey) + keyParams := sdk.NewKVStoreKey(paramstypes.StoreKey) + tkeyParams := sdk.NewTransientStoreKey(paramstypes.TStoreKey) keyGov := sdk.NewKVStoreKey(govtypes.StoreKey) db := dbm.NewMemDB() ms := store.NewCommitMultiStore(db) - ms.MountStoreWithDB(keyContract, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyWasm, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyAcc, sdk.StoreTypeIAVL, db) + ms.MountStoreWithDB(keyBank, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyParams, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyStaking, sdk.StoreTypeIAVL, db) - ms.MountStoreWithDB(keySupply, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(keyDistro, sdk.StoreTypeIAVL, db) ms.MountStoreWithDB(tkeyParams, sdk.StoreTypeTransient, db) ms.MountStoreWithDB(keyGov, sdk.StoreTypeIAVL, db) - err := ms.LoadLatestVersion() - require.Nil(t, err) + require.NoError(t, ms.LoadLatestVersion()) - ctx := sdk.NewContext(ms, abci.Header{ + ctx := sdk.NewContext(ms, tmproto.Header{ Height: 1234567, Time: time.Date(2020, time.April, 22, 12, 0, 0, 0, time.UTC), }, isCheckTx, log.NewNopLogger()) - cdc := MakeTestCodec() - - paramsKeeper := params.NewKeeper(cdc, keyParams, tkeyParams) - - accountKeeper := auth.NewAccountKeeper( - cdc, // amino codec + encodingConfig := MakeEncodingConfig + paramsKeeper := paramskeeper.NewKeeper(encodingConfig().Marshaler, encodingConfig().Amino, keyParams, tkeyParams) + paramsKeeper.Subspace(authtypes.ModuleName) + paramsKeeper.Subspace(banktypes.ModuleName) + paramsKeeper.Subspace(stakingtypes.ModuleName) + paramsKeeper.Subspace(minttypes.ModuleName) + paramsKeeper.Subspace(distributiontypes.ModuleName) + paramsKeeper.Subspace(slashingtypes.ModuleName) + paramsKeeper.Subspace(crisistypes.ModuleName) + + maccPerms := map[string][]string{ // module account permissions + authtypes.FeeCollectorName: nil, + distributiontypes.ModuleName: nil, + minttypes.ModuleName: {authtypes.Minter}, + stakingtypes.BondedPoolName: {authtypes.Burner, authtypes.Staking}, + stakingtypes.NotBondedPoolName: {authtypes.Burner, authtypes.Staking}, + govtypes.ModuleName: {authtypes.Burner}, + ibctransfertypes.ModuleName: {authtypes.Minter, authtypes.Burner}, + } + authSubsp, _ := paramsKeeper.GetSubspace(authtypes.ModuleName) + authKeeper := authkeeper.NewAccountKeeper( + encodingConfig().Marshaler, keyAcc, // target store - paramsKeeper.Subspace(auth.DefaultParamspace), - auth.ProtoBaseAccount, // prototype + authSubsp, + authtypes.ProtoBaseAccount, // prototype + maccPerms, ) - - // this is also used to initialize module accounts (so nil is meaningful here) - maccPerms := map[string][]string{ - auth.FeeCollectorName: nil, - distribution.ModuleName: nil, - //mint.ModuleName: {supply.Minter}, - staking.BondedPoolName: {supply.Burner, supply.Staking}, - staking.NotBondedPoolName: {supply.Burner, supply.Staking}, - gov.ModuleName: {supply.Burner}, - } - blockedAddr := make(map[string]bool, len(maccPerms)) + blockedAddrs := make(map[string]bool) for acc := range maccPerms { - blockedAddr[supply.NewModuleAddress(acc).String()] = true + allowReceivingFunds := acc != distributiontypes.ModuleName + blockedAddrs[authtypes.NewModuleAddress(acc).String()] = allowReceivingFunds } - bankKeeper := bank.NewBaseKeeper( - accountKeeper, - paramsKeeper.Subspace(bank.DefaultParamspace), - blockedAddr, + + bankSubsp, _ := paramsKeeper.GetSubspace(banktypes.ModuleName) + bankKeeper := bankkeeper.NewBaseKeeper( + encodingConfig().Marshaler, + keyBank, + authKeeper, + bankSubsp, + blockedAddrs, ) - bankKeeper.SetSendEnabled(ctx, true) + bankParams := banktypes.DefaultParams() + bankParams = bankParams.SetSendEnabledParam("stake", true) + bankKeeper.SetParams(ctx, bankParams) - supplyKeeper := supply.NewKeeper(cdc, keySupply, accountKeeper, bankKeeper, maccPerms) - stakingKeeper := staking.NewKeeper(cdc, keyStaking, supplyKeeper, paramsKeeper.Subspace(staking.DefaultParamspace)) + stakingSubsp, _ := paramsKeeper.GetSubspace(stakingtypes.ModuleName) + stakingKeeper := stakingkeeper.NewKeeper(encodingConfig().Marshaler, keyStaking, authKeeper, bankKeeper, stakingSubsp) stakingKeeper.SetParams(ctx, TestingStakeParams) - distKeeper := distribution.NewKeeper(cdc, keyDistro, paramsKeeper.Subspace(distribution.DefaultParamspace), stakingKeeper, supplyKeeper, auth.FeeCollectorName, nil) - distKeeper.SetParams(ctx, distribution.DefaultParams()) + distSubsp, _ := paramsKeeper.GetSubspace(distributiontypes.ModuleName) + distKeeper := distributionkeeper.NewKeeper(encodingConfig().Marshaler, keyDistro, distSubsp, authKeeper, bankKeeper, stakingKeeper, authtypes.FeeCollectorName, nil) + distKeeper.SetParams(ctx, distributiontypes.DefaultParams()) stakingKeeper.SetHooks(distKeeper.Hooks()) // set genesis items required for distribution - distKeeper.SetFeePool(ctx, distribution.InitialFeePool()) - - // total supply to track this - totalSupply := sdk.NewCoins(sdk.NewInt64Coin("stake", 100000000)) - supplyKeeper.SetSupply(ctx, supply.NewSupply(totalSupply)) - - // set up initial accounts - for name, perms := range maccPerms { - mod := supply.NewEmptyModuleAccount(name, perms...) - if name == staking.NotBondedPoolName { - err = mod.SetCoins(totalSupply) - require.NoError(t, err) - } else if name == distribution.ModuleName { - // some big pot to pay out - err = mod.SetCoins(sdk.NewCoins(sdk.NewInt64Coin("stake", 500000))) - require.NoError(t, err) - } - supplyKeeper.SetModuleAccount(ctx, mod) - } + distKeeper.SetFeePool(ctx, distributiontypes.InitialFeePool()) - stakeAddr := supply.NewModuleAddress(staking.BondedPoolName) - moduleAcct := accountKeeper.GetAccount(ctx, stakeAddr) - require.NotNil(t, moduleAcct) + // set some funds ot pay out validatores, based on code from: + // https://github.com/cosmos/cosmos-sdk/blob/fea231556aee4d549d7551a6190389c4328194eb/x/distribution/keeper/keeper_test.go#L50-L57 + distrAcc := distKeeper.GetDistributionAccount(ctx) + err = bankKeeper.SetBalances(ctx, distrAcc.GetAddress(), sdk.NewCoins( + sdk.NewCoin("stake", sdk.NewInt(2000000)), + )) + require.NoError(t, err) + authKeeper.SetModuleAccount(ctx, distrAcc) router := baseapp.NewRouter() bh := bank.NewHandler(bankKeeper) - router.AddRoute(bank.RouterKey, bh) + router.AddRoute(sdk.NewRoute(banktypes.RouterKey, bh)) sh := staking.NewHandler(stakingKeeper) - router.AddRoute(staking.RouterKey, sh) + router.AddRoute(sdk.NewRoute(stakingtypes.RouterKey, sh)) dh := distribution.NewHandler(distKeeper) - router.AddRoute(distribution.RouterKey, dh) + router.AddRoute(sdk.NewRoute(distributiontypes.RouterKey, dh)) // Load default wasm config - wasmConfig := wasmtypes.DefaultWasmConfig() - keeper := NewKeeper(cdc, keyContract, paramsKeeper.Subspace(wasmtypes.DefaultParamspace), - accountKeeper, bankKeeper, stakingKeeper, distKeeper, router, tempDir, wasmConfig, - supportedFeatures, encoders, queriers, + wasmConfig := wasmTypes.DefaultWasmConfig() + + keeper := NewKeeper( + encodingConfig().Marshaler, + keyWasm, + paramsKeeper.Subspace(wasmtypes.DefaultParamspace), + authKeeper, + bankKeeper, + stakingKeeper, + distKeeper, + router, + tempDir, + wasmConfig, + supportedFeatures, + encoders, + queriers, ) keeper.setParams(ctx, wasmtypes.DefaultParams()) // add wasm handler so we can loop-back (contracts calling contracts) - router.AddRoute(wasmtypes.RouterKey, TestHandler(keeper)) + router.AddRoute(sdk.NewRoute(wasmTypes.RouterKey, TestHandler(keeper))) - govRouter := gov.NewRouter(). - AddRoute(params.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). + govRouter := govtypes.NewRouter(). AddRoute(govtypes.RouterKey, govtypes.ProposalHandler). + AddRoute(paramproposal.RouterKey, params.NewParamChangeProposalHandler(paramsKeeper)). + AddRoute(distributiontypes.RouterKey, distribution.NewCommunityPoolSpendProposalHandler(distKeeper)). AddRoute(wasmtypes.RouterKey, NewWasmProposalHandler(keeper, wasmtypes.EnableAllProposals)) - govKeeper := gov.NewKeeper( - cdc, keyGov, paramsKeeper.Subspace(govtypes.DefaultParamspace).WithKeyTable(gov.ParamKeyTable()), supplyKeeper, stakingKeeper, govRouter, + govKeeper := govkeeper.NewKeeper( + encodingConfig().Marshaler, keyGov, paramsKeeper.Subspace(govtypes.ModuleName).WithKeyTable(govtypes.ParamKeyTable()), authKeeper, bankKeeper, stakingKeeper, govRouter, ) govKeeper.SetProposalID(ctx, govtypes.DefaultStartingProposalID) @@ -193,13 +264,12 @@ func CreateTestInput(t *testing.T, isCheckTx bool, tempDir string, supportedFeat govKeeper.SetTallyParams(ctx, govtypes.DefaultTallyParams()) keepers := TestKeepers{ - AccountKeeper: accountKeeper, - SupplyKeeper: supplyKeeper, + AccountKeeper: authKeeper, StakingKeeper: stakingKeeper, DistKeeper: distKeeper, WasmKeeper: keeper, - GovKeeper: govKeeper, BankKeeper: bankKeeper, + GovKeeper: govKeeper, } return ctx, keepers } @@ -210,13 +280,9 @@ func TestHandler(k Keeper) sdk.Handler { ctx = ctx.WithEventManager(sdk.NewEventManager()) switch msg := msg.(type) { - case wasmtypes.MsgInstantiateContract: - return handleInstantiate(ctx, k, &msg) case *wasmtypes.MsgInstantiateContract: return handleInstantiate(ctx, k, msg) - case wasmtypes.MsgExecuteContract: - return handleExecute(ctx, k, &msg) case *wasmtypes.MsgExecuteContract: return handleExecute(ctx, k, msg) @@ -235,7 +301,7 @@ func handleInstantiate(ctx sdk.Context, k Keeper, msg *wasmtypes.MsgInstantiateC return &sdk.Result{ Data: contractAddr, - Events: ctx.EventManager().Events(), + Events: ctx.EventManager().Events().ToABCIEvents(), }, nil } @@ -245,6 +311,90 @@ func handleExecute(ctx sdk.Context, k Keeper, msg *wasmtypes.MsgExecuteContract) return nil, err } - res.Events = ctx.EventManager().Events() + res.Events = ctx.EventManager().Events().ToABCIEvents() return res, nil } + +func AnyAccAddress(_ *testing.T) sdk.AccAddress { + _, _, addr := keyPubAddr() + return addr +} + +type HackatomExampleContract struct { + InitialAmount sdk.Coins + Contract sdk.AccAddress + Creator crypto.PrivKey + CreatorAddr sdk.AccAddress + Verifier crypto.PrivKey + VerifierAddr sdk.AccAddress + Beneficiary crypto.PrivKey + BeneficiaryAddr sdk.AccAddress +} + +// InstantiateHackatomExampleContract load and instantiate the "./testdata/hackatom.wasm" contract +func InstantiateHackatomExampleContract(t *testing.T, ctx sdk.Context, keepers TestKeepers) HackatomExampleContract { + anyAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 1000)) + creator, _, creatorAddr := keyPubAddr() + fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, creatorAddr, anyAmount) + verifier, _, verifierAddr := keyPubAddr() + fundAccounts(t, ctx, keepers.AccountKeeper, keepers.BankKeeper, verifierAddr, anyAmount) + + wasmCode, err := ioutil.ReadFile("./testdata/hackatom.wasm") + require.NoError(t, err) + + contractID, err := keepers.WasmKeeper.Create(ctx, creatorAddr, wasmCode, "", "", nil) + require.NoError(t, err) + + beneficiary, _, beneficiaryAddr := keyPubAddr() + initMsg := HackatomExampleInitMsg{ + Verifier: verifierAddr, + Beneficiary: beneficiaryAddr, + } + initMsgBz, err := json.Marshal(initMsg) + require.NoError(t, err) + initialAmount := sdk.NewCoins(sdk.NewInt64Coin("denom", 100)) + contractAddr, err := keepers.WasmKeeper.Instantiate(ctx, contractID, creatorAddr, nil, initMsgBz, "demo contract to query", initialAmount) + require.NoError(t, err) + return HackatomExampleContract{ + InitialAmount: initialAmount, + Contract: contractAddr, + Creator: creator, + CreatorAddr: creatorAddr, + Verifier: verifier, + VerifierAddr: verifierAddr, + Beneficiary: beneficiary, + BeneficiaryAddr: beneficiaryAddr, + } +} + +type HackatomExampleInitMsg struct { + Verifier sdk.AccAddress `json:"verifier"` + Beneficiary sdk.AccAddress `json:"beneficiary"` +} + +func createFakeFundedAccount(t *testing.T, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, coins sdk.Coins) sdk.AccAddress { + _, _, addr := keyPubAddr() + fundAccounts(t, ctx, am, bank, addr, coins) + return addr +} + +func fundAccounts(t *testing.T, ctx sdk.Context, am authkeeper.AccountKeeper, bank bankkeeper.Keeper, addr sdk.AccAddress, coins sdk.Coins) { + acc := am.NewAccountWithAddress(ctx, addr) + am.SetAccount(ctx, acc) + require.NoError(t, bank.SetBalances(ctx, addr, coins)) +} + +var keyCounter uint64 = 0 + +// we need to make this deterministic (same every test run), as encoded address size and thus gas cost, +// depends on the actual bytes (due to ugly CanonicalAddress encoding) +func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { + keyCounter++ + seed := make([]byte, 8) + binary.BigEndian.PutUint64(seed, keyCounter) + + key := ed25519.GenPrivKeyFromSecret(seed) + pub := key.PubKey() + addr := sdk.AccAddress(pub.Address()) + return key, pub, addr +} diff --git a/x/wasm/internal/keeper/test_fuzz.go b/x/wasm/internal/keeper/test_fuzz.go index d2e2338c37..c540a131df 100644 --- a/x/wasm/internal/keeper/test_fuzz.go +++ b/x/wasm/internal/keeper/test_fuzz.go @@ -44,22 +44,25 @@ func FuzzContractCodeHistory(m *types.ContractCodeHistoryEntry, c fuzz.Continue) func FuzzStateModel(m *types.Model, c fuzz.Continue) { m.Key = tmBytes.HexBytes(c.RandString()) + if len(m.Key) == 0 { + m.Key = tmBytes.HexBytes("non empty key") + } c.Fuzz(&m.Value) } func FuzzAccessType(m *types.AccessType, c fuzz.Continue) { pos := c.Int() % len(types.AllAccessTypes) - for k := range types.AllAccessTypes { + for _, v := range types.AllAccessTypes { if pos == 0 { - *m = k + *m = v return } pos-- } } func FuzzAccessConfig(m *types.AccessConfig, c fuzz.Continue) { - FuzzAccessType(&m.Type, c) + FuzzAccessType(&m.Permission, c) var add sdk.AccAddress FuzzAddr(&add, c) - *m = m.Type.With(add) + *m = m.Permission.With(add) } diff --git a/x/wasm/internal/types/codec.go b/x/wasm/internal/types/codec.go index fcc1c861b6..5a7e3b0c0b 100644 --- a/x/wasm/internal/types/codec.go +++ b/x/wasm/internal/types/codec.go @@ -2,10 +2,14 @@ package types import ( "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + sdk "github.com/cosmos/cosmos-sdk/types" + govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" ) -// RegisterCodec registers the account types and interface -func RegisterCodec(cdc *codec.Codec) { +// RegisterLegacyAminoCodec registers the account types and interface +func RegisterLegacyAminoCodec(cdc *codec.LegacyAmino) { cdc.RegisterConcrete(MsgStoreCode{}, "wasm/MsgStoreCode", nil) cdc.RegisterConcrete(MsgInstantiateContract{}, "wasm/MsgInstantiateContract", nil) cdc.RegisterConcrete(MsgExecuteContract{}, "wasm/MsgExecuteContract", nil) @@ -20,12 +24,36 @@ func RegisterCodec(cdc *codec.Codec) { cdc.RegisterConcrete(ClearAdminProposal{}, "wasm/ClearAdminProposal", nil) } -// ModuleCdc generic sealed codec to be used throughout module -var ModuleCdc *codec.Codec +func RegisterInterfaces(registry types.InterfaceRegistry) { + registry.RegisterImplementations( + (*sdk.Msg)(nil), + &MsgStoreCode{}, + &MsgInstantiateContract{}, + &MsgExecuteContract{}, + &MsgMigrateContract{}, + &MsgUpdateAdmin{}, + &MsgClearAdmin{}, + ) + registry.RegisterImplementations( + (*govtypes.Content)(nil), + &StoreCodeProposal{}, + &InstantiateContractProposal{}, + &MigrateContractProposal{}, + &UpdateAdminProposal{}, + &ClearAdminProposal{}, + ) +} + +var ( + amino = codec.NewLegacyAmino() + + // ModuleCdc references the global x/wasm module codec. + + ModuleCdc = codec.NewAminoCodec(amino) +) func init() { - cdc := codec.New() - RegisterCodec(cdc) - codec.RegisterCrypto(cdc) - ModuleCdc = cdc.Seal() + RegisterLegacyAminoCodec(amino) + cryptocodec.RegisterCrypto(amino) + amino.Seal() } diff --git a/x/wasm/internal/types/genesis.go b/x/wasm/internal/types/genesis.go index 14a546c02d..e53846bb6b 100644 --- a/x/wasm/internal/types/genesis.go +++ b/x/wasm/internal/types/genesis.go @@ -6,11 +6,6 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -type Sequence struct { - IDKey []byte `json:"id_key"` - Value uint64 `json:"value"` -} - func (s Sequence) ValidateBasic() error { if len(s.IDKey) == 0 { return sdkerrors.Wrap(ErrEmpty, "id key") @@ -18,14 +13,6 @@ func (s Sequence) ValidateBasic() error { return nil } -// GenesisState is the struct representation of the export genesis -type GenesisState struct { - Params Params `json:"params"` - Codes []Code `json:"codes,omitempty"` - Contracts []Contract `json:"contracts,omitempty"` - Sequences []Sequence `json:"sequences,omitempty"` -} - func (s GenesisState) ValidateBasic() error { if err := s.Params.ValidateBasic(); err != nil { return sdkerrors.Wrap(err, "params") @@ -48,13 +35,6 @@ func (s GenesisState) ValidateBasic() error { return nil } -// Code struct encompasses CodeInfo and CodeBytes -type Code struct { - CodeID uint64 `json:"code_id"` - CodeInfo CodeInfo `json:"code_info"` - CodesBytes []byte `json:"code_bytes"` -} - func (c Code) ValidateBasic() error { if c.CodeID == 0 { return sdkerrors.Wrap(ErrEmpty, "code id") @@ -62,19 +42,12 @@ func (c Code) ValidateBasic() error { if err := c.CodeInfo.ValidateBasic(); err != nil { return sdkerrors.Wrap(err, "code info") } - if err := validateWasmCode(c.CodesBytes); err != nil { + if err := validateWasmCode(c.CodeBytes); err != nil { return sdkerrors.Wrap(err, "code bytes") } return nil } -// Contract struct encompasses ContractAddress, ContractInfo, and ContractState -type Contract struct { - ContractAddress sdk.AccAddress `json:"contract_address"` - ContractInfo ContractInfo `json:"contract_info"` - ContractState []Model `json:"contract_state"` -} - func (c Contract) ValidateBasic() error { if err := sdk.VerifyAddressFormat(c.ContractAddress); err != nil { return sdkerrors.Wrap(err, "contract address") diff --git a/x/wasm/internal/types/genesis.pb.go b/x/wasm/internal/types/genesis.pb.go new file mode 100644 index 0000000000..ac67c197bb --- /dev/null +++ b/x/wasm/internal/types/genesis.pb.go @@ -0,0 +1,1300 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: x/wasm/internal/types/genesis.proto + +package types + +import ( + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// GenesisState - genesis state of x/wasm +type GenesisState struct { + Params Params `protobuf:"bytes,1,opt,name=params,proto3" json:"params"` + Codes []Code `protobuf:"bytes,2,rep,name=codes,proto3" json:"codes,omitempty"` + Contracts []Contract `protobuf:"bytes,3,rep,name=contracts,proto3" json:"contracts,omitempty"` + Sequences []Sequence `protobuf:"bytes,4,rep,name=sequences,proto3" json:"sequences,omitempty"` +} + +func (m *GenesisState) Reset() { *m = GenesisState{} } +func (m *GenesisState) String() string { return proto.CompactTextString(m) } +func (*GenesisState) ProtoMessage() {} +func (*GenesisState) Descriptor() ([]byte, []int) { + return fileDescriptor_52f9f2715025dba8, []int{0} +} +func (m *GenesisState) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *GenesisState) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_GenesisState.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *GenesisState) XXX_Merge(src proto.Message) { + xxx_messageInfo_GenesisState.Merge(m, src) +} +func (m *GenesisState) XXX_Size() int { + return m.Size() +} +func (m *GenesisState) XXX_DiscardUnknown() { + xxx_messageInfo_GenesisState.DiscardUnknown(m) +} + +var xxx_messageInfo_GenesisState proto.InternalMessageInfo + +func (m *GenesisState) GetParams() Params { + if m != nil { + return m.Params + } + return Params{} +} + +func (m *GenesisState) GetCodes() []Code { + if m != nil { + return m.Codes + } + return nil +} + +func (m *GenesisState) GetContracts() []Contract { + if m != nil { + return m.Contracts + } + return nil +} + +func (m *GenesisState) GetSequences() []Sequence { + if m != nil { + return m.Sequences + } + return nil +} + +// Code struct encompasses CodeInfo and CodeBytes +type Code struct { + CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + CodeInfo CodeInfo `protobuf:"bytes,2,opt,name=code_info,json=codeInfo,proto3" json:"code_info"` + CodeBytes []byte `protobuf:"bytes,3,opt,name=code_bytes,json=codeBytes,proto3" json:"code_bytes,omitempty"` +} + +func (m *Code) Reset() { *m = Code{} } +func (m *Code) String() string { return proto.CompactTextString(m) } +func (*Code) ProtoMessage() {} +func (*Code) Descriptor() ([]byte, []int) { + return fileDescriptor_52f9f2715025dba8, []int{1} +} +func (m *Code) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Code) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Code.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Code) XXX_Merge(src proto.Message) { + xxx_messageInfo_Code.Merge(m, src) +} +func (m *Code) XXX_Size() int { + return m.Size() +} +func (m *Code) XXX_DiscardUnknown() { + xxx_messageInfo_Code.DiscardUnknown(m) +} + +var xxx_messageInfo_Code proto.InternalMessageInfo + +func (m *Code) GetCodeID() uint64 { + if m != nil { + return m.CodeID + } + return 0 +} + +func (m *Code) GetCodeInfo() CodeInfo { + if m != nil { + return m.CodeInfo + } + return CodeInfo{} +} + +func (m *Code) GetCodeBytes() []byte { + if m != nil { + return m.CodeBytes + } + return nil +} + +// Contract struct encompasses ContractAddress, ContractInfo, and ContractState +type Contract struct { + ContractAddress github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=contract_address,json=contractAddress,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract_address,omitempty"` + ContractInfo ContractInfo `protobuf:"bytes,2,opt,name=contract_info,json=contractInfo,proto3" json:"contract_info"` + ContractState []Model `protobuf:"bytes,3,rep,name=contract_state,json=contractState,proto3" json:"contract_state"` +} + +func (m *Contract) Reset() { *m = Contract{} } +func (m *Contract) String() string { return proto.CompactTextString(m) } +func (*Contract) ProtoMessage() {} +func (*Contract) Descriptor() ([]byte, []int) { + return fileDescriptor_52f9f2715025dba8, []int{2} +} +func (m *Contract) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Contract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Contract.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Contract) XXX_Merge(src proto.Message) { + xxx_messageInfo_Contract.Merge(m, src) +} +func (m *Contract) XXX_Size() int { + return m.Size() +} +func (m *Contract) XXX_DiscardUnknown() { + xxx_messageInfo_Contract.DiscardUnknown(m) +} + +var xxx_messageInfo_Contract proto.InternalMessageInfo + +func (m *Contract) GetContractAddress() github_com_cosmos_cosmos_sdk_types.AccAddress { + if m != nil { + return m.ContractAddress + } + return nil +} + +func (m *Contract) GetContractInfo() ContractInfo { + if m != nil { + return m.ContractInfo + } + return ContractInfo{} +} + +func (m *Contract) GetContractState() []Model { + if m != nil { + return m.ContractState + } + return nil +} + +// Sequence id and value of a counter +type Sequence struct { + IDKey []byte `protobuf:"bytes,1,opt,name=id_key,json=idKey,proto3" json:"id_key,omitempty"` + Value uint64 `protobuf:"varint,2,opt,name=value,proto3" json:"value,omitempty"` +} + +func (m *Sequence) Reset() { *m = Sequence{} } +func (m *Sequence) String() string { return proto.CompactTextString(m) } +func (*Sequence) ProtoMessage() {} +func (*Sequence) Descriptor() ([]byte, []int) { + return fileDescriptor_52f9f2715025dba8, []int{3} +} +func (m *Sequence) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Sequence) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Sequence.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Sequence) XXX_Merge(src proto.Message) { + xxx_messageInfo_Sequence.Merge(m, src) +} +func (m *Sequence) XXX_Size() int { + return m.Size() +} +func (m *Sequence) XXX_DiscardUnknown() { + xxx_messageInfo_Sequence.DiscardUnknown(m) +} + +var xxx_messageInfo_Sequence proto.InternalMessageInfo + +func (m *Sequence) GetIDKey() []byte { + if m != nil { + return m.IDKey + } + return nil +} + +func (m *Sequence) GetValue() uint64 { + if m != nil { + return m.Value + } + return 0 +} + +func init() { + proto.RegisterType((*GenesisState)(nil), "wasmd.x.wasmd.v1beta1.GenesisState") + proto.RegisterType((*Code)(nil), "wasmd.x.wasmd.v1beta1.Code") + proto.RegisterType((*Contract)(nil), "wasmd.x.wasmd.v1beta1.Contract") + proto.RegisterType((*Sequence)(nil), "wasmd.x.wasmd.v1beta1.Sequence") +} + +func init() { + proto.RegisterFile("x/wasm/internal/types/genesis.proto", fileDescriptor_52f9f2715025dba8) +} + +var fileDescriptor_52f9f2715025dba8 = []byte{ + // 531 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x93, 0x41, 0x6f, 0xd3, 0x30, + 0x14, 0xc7, 0x9b, 0xae, 0x0d, 0x9d, 0x57, 0x18, 0x32, 0x43, 0x44, 0x1b, 0x4b, 0x4a, 0x7b, 0xe9, + 0x81, 0x25, 0x74, 0x1c, 0x39, 0x2d, 0x9b, 0x84, 0xb2, 0x09, 0x84, 0xb2, 0x03, 0xd2, 0x84, 0x54, + 0xa5, 0xb6, 0x57, 0xa2, 0x35, 0x71, 0x89, 0xdd, 0xd1, 0x9c, 0xb9, 0x23, 0x3e, 0xd6, 0x6e, 0xec, + 0xc8, 0x29, 0x42, 0xe9, 0x8d, 0x8f, 0xc0, 0x09, 0xd9, 0x71, 0xb3, 0x20, 0xad, 0xdb, 0x25, 0x8e, + 0x9f, 0xff, 0xef, 0x67, 0xbf, 0xbf, 0x9f, 0x41, 0x6f, 0xee, 0x7c, 0x0d, 0x58, 0xe4, 0x84, 0x31, + 0x27, 0x49, 0x1c, 0x4c, 0x1c, 0x9e, 0x4e, 0x09, 0x73, 0xc6, 0x24, 0x26, 0x2c, 0x64, 0xf6, 0x34, + 0xa1, 0x9c, 0xc2, 0xa7, 0x42, 0x82, 0xed, 0xb9, 0x5d, 0x8c, 0x97, 0x83, 0x11, 0xe1, 0xc1, 0x60, + 0x7b, 0x6b, 0x4c, 0xc7, 0x54, 0x2a, 0x1c, 0xf1, 0x57, 0x88, 0xb7, 0x5f, 0xdc, 0x4e, 0x94, 0xdf, + 0x42, 0xd2, 0xfd, 0x59, 0x07, 0xed, 0xb7, 0xc5, 0x0e, 0xa7, 0x3c, 0xe0, 0x04, 0xbe, 0x01, 0xfa, + 0x34, 0x48, 0x82, 0x88, 0x19, 0x5a, 0x47, 0xeb, 0x6f, 0xec, 0xef, 0xda, 0xb7, 0xee, 0x68, 0x7f, + 0x90, 0x22, 0xb7, 0x71, 0x95, 0x59, 0x35, 0x5f, 0xa5, 0xc0, 0x63, 0xd0, 0x44, 0x14, 0x13, 0x66, + 0xd4, 0x3b, 0x6b, 0xfd, 0x8d, 0xfd, 0x9d, 0x15, 0xb9, 0x87, 0x14, 0x13, 0xf7, 0x99, 0xc8, 0xfc, + 0x93, 0x59, 0x9b, 0x32, 0xe3, 0x25, 0x8d, 0x42, 0x4e, 0xa2, 0x29, 0x4f, 0xfd, 0x02, 0x01, 0xcf, + 0xc0, 0x3a, 0xa2, 0x31, 0x4f, 0x02, 0xc4, 0x99, 0xb1, 0x26, 0x79, 0xd6, 0x4a, 0x5e, 0xa1, 0x73, + 0x77, 0x14, 0xf3, 0x49, 0x99, 0x59, 0xe1, 0xde, 0xe0, 0x04, 0x9b, 0x91, 0x2f, 0x33, 0x12, 0x23, + 0xc2, 0x8c, 0xc6, 0x9d, 0xec, 0x53, 0xa5, 0xbb, 0x61, 0x97, 0x99, 0x55, 0x76, 0x19, 0xec, 0x7e, + 0xd7, 0x40, 0x43, 0x14, 0x08, 0x7b, 0xe0, 0x81, 0xa8, 0x64, 0x18, 0x62, 0x69, 0x65, 0xc3, 0x05, + 0x79, 0x66, 0xe9, 0x62, 0xc9, 0x3b, 0xf2, 0x75, 0xb1, 0xe4, 0x61, 0xe8, 0x8a, 0x2a, 0x85, 0x28, + 0x3e, 0xa7, 0x46, 0x5d, 0x3a, 0x6e, 0xdd, 0xe1, 0x9a, 0x17, 0x9f, 0x53, 0xe5, 0x79, 0x0b, 0xa9, + 0x39, 0xdc, 0x05, 0x40, 0x32, 0x46, 0x29, 0x27, 0xc2, 0x2a, 0xad, 0xdf, 0xf6, 0x25, 0xd5, 0x15, + 0x81, 0xee, 0xb7, 0x3a, 0x68, 0x2d, 0x1d, 0x82, 0x9f, 0xc0, 0xe3, 0xa5, 0x0d, 0xc3, 0x00, 0xe3, + 0x84, 0xb0, 0xe2, 0xa2, 0xdb, 0xee, 0xe0, 0x6f, 0x66, 0xed, 0x8d, 0x43, 0xfe, 0x79, 0x36, 0xb2, + 0x11, 0x8d, 0x1c, 0x44, 0x59, 0x44, 0x99, 0x1a, 0xf6, 0x18, 0xbe, 0x50, 0x7d, 0x73, 0x80, 0xd0, + 0x41, 0x91, 0xe8, 0x6f, 0x2e, 0x51, 0x2a, 0x00, 0xdf, 0x83, 0x87, 0x25, 0xbd, 0x52, 0x51, 0xef, + 0x9e, 0x7b, 0xab, 0x54, 0xd5, 0x46, 0x95, 0x18, 0xf4, 0xc0, 0xa3, 0x92, 0xc7, 0x44, 0x7b, 0xaa, + 0x46, 0x78, 0xbe, 0x02, 0xf8, 0x8e, 0x62, 0x32, 0x51, 0xa4, 0xf2, 0x24, 0xb2, 0xaf, 0xbb, 0x2e, + 0x68, 0x2d, 0xaf, 0x12, 0x76, 0x80, 0x1e, 0xe2, 0xe1, 0x05, 0x49, 0x55, 0xe9, 0xeb, 0x79, 0x66, + 0x35, 0xbd, 0xa3, 0x13, 0x92, 0xfa, 0xcd, 0x10, 0x9f, 0x90, 0x14, 0x6e, 0x81, 0xe6, 0x65, 0x30, + 0x99, 0x11, 0x59, 0x40, 0xc3, 0x2f, 0x26, 0xee, 0xf1, 0x55, 0x6e, 0x6a, 0xd7, 0xb9, 0xa9, 0xfd, + 0xce, 0x4d, 0xed, 0xc7, 0xc2, 0xac, 0x5d, 0x2f, 0xcc, 0xda, 0xaf, 0x85, 0x59, 0x3b, 0x7b, 0x55, + 0x31, 0xee, 0x90, 0xb2, 0xe8, 0xa3, 0x78, 0x76, 0xf2, 0x6c, 0xce, 0x5c, 0x8d, 0xff, 0x3f, 0xc2, + 0x91, 0x2e, 0xdf, 0xdf, 0xeb, 0x7f, 0x01, 0x00, 0x00, 0xff, 0xff, 0xf9, 0xd1, 0x3c, 0xa8, 0xf6, + 0x03, 0x00, 0x00, +} + +func (m *GenesisState) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *GenesisState) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *GenesisState) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Sequences) > 0 { + for iNdEx := len(m.Sequences) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Sequences[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + } + } + if len(m.Contracts) > 0 { + for iNdEx := len(m.Contracts) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Contracts[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.Codes) > 0 { + for iNdEx := len(m.Codes) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Codes[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + { + size, err := m.Params.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *Code) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Code) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Code) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CodeBytes) > 0 { + i -= len(m.CodeBytes) + copy(dAtA[i:], m.CodeBytes) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.CodeBytes))) + i-- + dAtA[i] = 0x1a + } + { + size, err := m.CodeInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if m.CodeID != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Contract) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Contract) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Contract) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ContractState) > 0 { + for iNdEx := len(m.ContractState) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ContractState[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + { + size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintGenesis(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + if len(m.ContractAddress) > 0 { + i -= len(m.ContractAddress) + copy(dAtA[i:], m.ContractAddress) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.ContractAddress))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *Sequence) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Sequence) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Sequence) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Value != 0 { + i = encodeVarintGenesis(dAtA, i, uint64(m.Value)) + i-- + dAtA[i] = 0x10 + } + if len(m.IDKey) > 0 { + i -= len(m.IDKey) + copy(dAtA[i:], m.IDKey) + i = encodeVarintGenesis(dAtA, i, uint64(len(m.IDKey))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintGenesis(dAtA []byte, offset int, v uint64) int { + offset -= sovGenesis(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *GenesisState) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.Params.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.Codes) > 0 { + for _, e := range m.Codes { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.Contracts) > 0 { + for _, e := range m.Contracts { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + if len(m.Sequences) > 0 { + for _, e := range m.Sequences { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *Code) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeID != 0 { + n += 1 + sovGenesis(uint64(m.CodeID)) + } + l = m.CodeInfo.Size() + n += 1 + l + sovGenesis(uint64(l)) + l = len(m.CodeBytes) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + return n +} + +func (m *Contract) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.ContractAddress) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + l = m.ContractInfo.Size() + n += 1 + l + sovGenesis(uint64(l)) + if len(m.ContractState) > 0 { + for _, e := range m.ContractState { + l = e.Size() + n += 1 + l + sovGenesis(uint64(l)) + } + } + return n +} + +func (m *Sequence) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.IDKey) + if l > 0 { + n += 1 + l + sovGenesis(uint64(l)) + } + if m.Value != 0 { + n += 1 + sovGenesis(uint64(m.Value)) + } + return n +} + +func sovGenesis(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozGenesis(x uint64) (n int) { + return sovGenesis(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *GenesisState) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: GenesisState: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: GenesisState: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Params", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.Params.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Codes", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Codes = append(m.Codes, Code{}) + if err := m.Codes[len(m.Codes)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contracts", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contracts = append(m.Contracts, Contract{}) + if err := m.Contracts[len(m.Contracts)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sequences", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sequences = append(m.Sequences, Sequence{}) + if err := m.Sequences[len(m.Sequences)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Code) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Code: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Code: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.CodeInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeBytes", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CodeBytes = append(m.CodeBytes[:0], dAtA[iNdEx:postIndex]...) + if m.CodeBytes == nil { + m.CodeBytes = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Contract) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Contract: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Contract: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractAddress", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ContractAddress = append(m.ContractAddress[:0], dAtA[iNdEx:postIndex]...) + if m.ContractAddress == nil { + m.ContractAddress = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractState", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ContractState = append(m.ContractState, Model{}) + if err := m.ContractState[len(m.ContractState)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Sequence) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Sequence: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Sequence: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field IDKey", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthGenesis + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthGenesis + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.IDKey = append(m.IDKey[:0], dAtA[iNdEx:postIndex]...) + if m.IDKey == nil { + m.IDKey = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + m.Value = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowGenesis + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Value |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipGenesis(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthGenesis + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipGenesis(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowGenesis + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthGenesis + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupGenesis + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthGenesis + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthGenesis = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowGenesis = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupGenesis = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/wasm/internal/types/genesis.proto b/x/wasm/internal/types/genesis.proto new file mode 100644 index 0000000000..cf5529b28d --- /dev/null +++ b/x/wasm/internal/types/genesis.proto @@ -0,0 +1,35 @@ +syntax = "proto3"; +package wasmd.x.wasmd.v1beta1; + +import "gogoproto/gogo.proto"; +import "x/wasm/internal/types/types.proto"; + +option go_package = "github.com/CosmWasm/wasmd/x/wasmd/internal/types"; + +// GenesisState - genesis state of x/wasm +message GenesisState { + Params params = 1 [(gogoproto.nullable) = false]; + repeated Code codes = 2 [(gogoproto.nullable) = false, (gogoproto.jsontag) = "codes,omitempty"]; + repeated Contract contracts = 3 [(gogoproto.nullable) = false, (gogoproto.jsontag) = "contracts,omitempty"]; + repeated Sequence sequences = 4 [(gogoproto.nullable) = false, (gogoproto.jsontag) = "sequences,omitempty"]; +} + +// Code struct encompasses CodeInfo and CodeBytes +message Code { + uint64 code_id = 1 [(gogoproto.customname) = "CodeID"]; + CodeInfo code_info = 2 [(gogoproto.nullable) = false]; + bytes code_bytes = 3; +} + +// Contract struct encompasses ContractAddress, ContractInfo, and ContractState +message Contract { + bytes contract_address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + ContractInfo contract_info = 2 [(gogoproto.nullable) = false]; + repeated Model contract_state = 3 [(gogoproto.nullable) = false]; +} + +// Sequence id and value of a counter +message Sequence { + bytes id_key = 1 [(gogoproto.customname) = "IDKey"]; + uint64 value = 2; +} \ No newline at end of file diff --git a/x/wasm/internal/types/genesis_test.go b/x/wasm/internal/types/genesis_test.go index 94ebe185e8..af98ec808a 100644 --- a/x/wasm/internal/types/genesis_test.go +++ b/x/wasm/internal/types/genesis_test.go @@ -73,19 +73,19 @@ func TestCodeValidateBasic(t *testing.T) { }, "codeBytes empty": { srcMutator: func(c *Code) { - c.CodesBytes = []byte{} + c.CodeBytes = []byte{} }, expError: true, }, "codeBytes nil": { srcMutator: func(c *Code) { - c.CodesBytes = nil + c.CodeBytes = nil }, expError: true, }, "codeBytes greater limit": { srcMutator: func(c *Code) { - c.CodesBytes = bytes.Repeat([]byte{0x1}, MaxWasmSize+1) + c.CodeBytes = bytes.Repeat([]byte{0x1}, MaxWasmSize+1) }, expError: true, }, diff --git a/x/wasm/internal/types/iavl_range_test.go b/x/wasm/internal/types/iavl_range_test.go index 4af414743b..bc852a6b54 100644 --- a/x/wasm/internal/types/iavl_range_test.go +++ b/x/wasm/internal/types/iavl_range_test.go @@ -3,8 +3,8 @@ package types import ( "github.com/cosmos/cosmos-sdk/store" "github.com/cosmos/cosmos-sdk/store/iavl" + iavl2 "github.com/cosmos/iavl" "github.com/stretchr/testify/require" - iavl2 "github.com/tendermint/iavl" dbm "github.com/tendermint/tm-db" "testing" ) diff --git a/x/wasm/internal/types/msg.go b/x/wasm/internal/types/msg.go index 43ee4be6b7..b41a63a468 100644 --- a/x/wasm/internal/types/msg.go +++ b/x/wasm/internal/types/msg.go @@ -7,18 +7,6 @@ import ( sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -type MsgStoreCode struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `json:"wasm_byte_code" yaml:"wasm_byte_code"` - // Source is a valid absolute HTTPS URI to the contract's source code, optional - Source string `json:"source" yaml:"source"` - // Builder is a valid docker image name with tag, optional - Builder string `json:"builder" yaml:"builder"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `json:"instantiate_permission,omitempty" yaml:"instantiate_permission"` -} - func (msg MsgStoreCode) Route() string { return RouterKey } @@ -52,23 +40,14 @@ func (msg MsgStoreCode) ValidateBasic() error { } func (msg MsgStoreCode) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgStoreCode) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } -type MsgInstantiateContract struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - // Admin is an optional address that can execute migrations - Admin sdk.AccAddress `json:"admin,omitempty" yaml:"admin"` - CodeID uint64 `json:"code_id" yaml:"code_id"` - Label string `json:"label" yaml:"label"` - InitMsg json.RawMessage `json:"init_msg" yaml:"init_msg"` - InitFunds sdk.Coins `json:"init_funds" yaml:"init_funds"` -} - func (msg MsgInstantiateContract) Route() string { return RouterKey } @@ -106,20 +85,14 @@ func (msg MsgInstantiateContract) ValidateBasic() error { } func (msg MsgInstantiateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgInstantiateContract) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } -type MsgExecuteContract struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Contract sdk.AccAddress `json:"contract" yaml:"contract"` - Msg json.RawMessage `json:"msg" yaml:"msg"` - SentFunds sdk.Coins `json:"sent_funds" yaml:"sent_funds"` -} - func (msg MsgExecuteContract) Route() string { return RouterKey } @@ -146,20 +119,14 @@ func (msg MsgExecuteContract) ValidateBasic() error { } func (msg MsgExecuteContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgExecuteContract) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } -type MsgMigrateContract struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Contract sdk.AccAddress `json:"contract" yaml:"contract"` - CodeID uint64 `json:"code_id" yaml:"code_id"` - MigrateMsg json.RawMessage `json:"msg" yaml:"msg"` -} - func (msg MsgMigrateContract) Route() string { return RouterKey } @@ -186,19 +153,14 @@ func (msg MsgMigrateContract) ValidateBasic() error { } func (msg MsgMigrateContract) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgMigrateContract) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } -type MsgUpdateAdmin struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - NewAdmin sdk.AccAddress `json:"new_admin" yaml:"new_admin"` - Contract sdk.AccAddress `json:"contract" yaml:"contract"` -} - func (msg MsgUpdateAdmin) Route() string { return RouterKey } @@ -224,18 +186,14 @@ func (msg MsgUpdateAdmin) ValidateBasic() error { } func (msg MsgUpdateAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgUpdateAdmin) GetSigners() []sdk.AccAddress { return []sdk.AccAddress{msg.Sender} } -type MsgClearAdmin struct { - Sender sdk.AccAddress `json:"sender" yaml:"sender"` - Contract sdk.AccAddress `json:"contract" yaml:"contract"` -} - func (msg MsgClearAdmin) Route() string { return RouterKey } @@ -255,7 +213,8 @@ func (msg MsgClearAdmin) ValidateBasic() error { } func (msg MsgClearAdmin) GetSignBytes() []byte { - return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(msg)) + return sdk.MustSortJSON(ModuleCdc.MustMarshalJSON(&msg)) + } func (msg MsgClearAdmin) GetSigners() []sdk.AccAddress { diff --git a/x/wasm/internal/types/msg.pb.go b/x/wasm/internal/types/msg.pb.go new file mode 100644 index 0000000000..68d7193304 --- /dev/null +++ b/x/wasm/internal/types/msg.pb.go @@ -0,0 +1,2004 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: x/wasm/internal/types/msg.proto + +package types + +import ( + encoding_json "encoding/json" + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type MsgStoreCode struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + // WASMByteCode can be raw or gzip compressed + WASMByteCode []byte `protobuf:"bytes,2,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` + // Source is a valid absolute HTTPS URI to the contract's source code, optional + Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` + // Builder is a valid docker image name with tag, optional + Builder string `protobuf:"bytes,4,opt,name=builder,proto3" json:"builder,omitempty"` + // InstantiatePermission to apply on contract creation, optional + InstantiatePermission *AccessConfig `protobuf:"bytes,5,opt,name=InstantiatePermission,proto3" json:"InstantiatePermission,omitempty"` +} + +func (m *MsgStoreCode) Reset() { *m = MsgStoreCode{} } +func (m *MsgStoreCode) String() string { return proto.CompactTextString(m) } +func (*MsgStoreCode) ProtoMessage() {} +func (*MsgStoreCode) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{0} +} +func (m *MsgStoreCode) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgStoreCode) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgStoreCode.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgStoreCode) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgStoreCode.Merge(m, src) +} +func (m *MsgStoreCode) XXX_Size() int { + return m.Size() +} +func (m *MsgStoreCode) XXX_DiscardUnknown() { + xxx_messageInfo_MsgStoreCode.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgStoreCode proto.InternalMessageInfo + +type MsgInstantiateContract struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + // Admin is an optional address that can execute migrations + Admin github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=admin,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"admin,omitempty"` + CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` + InitMsg encoding_json.RawMessage `protobuf:"bytes,5,opt,name=init_msg,json=initMsg,proto3,casttype=encoding/json.RawMessage" json:"init_msg,omitempty"` + InitFunds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,6,rep,name=init_funds,json=initFunds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"init_funds"` +} + +func (m *MsgInstantiateContract) Reset() { *m = MsgInstantiateContract{} } +func (m *MsgInstantiateContract) String() string { return proto.CompactTextString(m) } +func (*MsgInstantiateContract) ProtoMessage() {} +func (*MsgInstantiateContract) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{1} +} +func (m *MsgInstantiateContract) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgInstantiateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgInstantiateContract.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgInstantiateContract) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgInstantiateContract.Merge(m, src) +} +func (m *MsgInstantiateContract) XXX_Size() int { + return m.Size() +} +func (m *MsgInstantiateContract) XXX_DiscardUnknown() { + xxx_messageInfo_MsgInstantiateContract.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgInstantiateContract proto.InternalMessageInfo + +type MsgExecuteContract struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` + Msg encoding_json.RawMessage `protobuf:"bytes,3,opt,name=msg,proto3,casttype=encoding/json.RawMessage" json:"msg,omitempty"` + SentFunds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=sent_funds,json=sentFunds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"sent_funds"` +} + +func (m *MsgExecuteContract) Reset() { *m = MsgExecuteContract{} } +func (m *MsgExecuteContract) String() string { return proto.CompactTextString(m) } +func (*MsgExecuteContract) ProtoMessage() {} +func (*MsgExecuteContract) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{2} +} +func (m *MsgExecuteContract) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgExecuteContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgExecuteContract.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgExecuteContract) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgExecuteContract.Merge(m, src) +} +func (m *MsgExecuteContract) XXX_Size() int { + return m.Size() +} +func (m *MsgExecuteContract) XXX_DiscardUnknown() { + xxx_messageInfo_MsgExecuteContract.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgExecuteContract proto.InternalMessageInfo + +type MsgMigrateContract struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` + CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + MigrateMsg encoding_json.RawMessage `protobuf:"bytes,4,opt,name=migrate_msg,json=migrateMsg,proto3,casttype=encoding/json.RawMessage" json:"migrate_msg,omitempty"` +} + +func (m *MsgMigrateContract) Reset() { *m = MsgMigrateContract{} } +func (m *MsgMigrateContract) String() string { return proto.CompactTextString(m) } +func (*MsgMigrateContract) ProtoMessage() {} +func (*MsgMigrateContract) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{3} +} +func (m *MsgMigrateContract) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgMigrateContract) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgMigrateContract.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgMigrateContract) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgMigrateContract.Merge(m, src) +} +func (m *MsgMigrateContract) XXX_Size() int { + return m.Size() +} +func (m *MsgMigrateContract) XXX_DiscardUnknown() { + xxx_messageInfo_MsgMigrateContract.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgMigrateContract proto.InternalMessageInfo + +type MsgUpdateAdmin struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + NewAdmin github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=new_admin,json=newAdmin,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"new_admin,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` +} + +func (m *MsgUpdateAdmin) Reset() { *m = MsgUpdateAdmin{} } +func (m *MsgUpdateAdmin) String() string { return proto.CompactTextString(m) } +func (*MsgUpdateAdmin) ProtoMessage() {} +func (*MsgUpdateAdmin) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{4} +} +func (m *MsgUpdateAdmin) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgUpdateAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgUpdateAdmin.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgUpdateAdmin) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgUpdateAdmin.Merge(m, src) +} +func (m *MsgUpdateAdmin) XXX_Size() int { + return m.Size() +} +func (m *MsgUpdateAdmin) XXX_DiscardUnknown() { + xxx_messageInfo_MsgUpdateAdmin.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgUpdateAdmin proto.InternalMessageInfo + +type MsgClearAdmin struct { + Sender github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=sender,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"sender,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` +} + +func (m *MsgClearAdmin) Reset() { *m = MsgClearAdmin{} } +func (m *MsgClearAdmin) String() string { return proto.CompactTextString(m) } +func (*MsgClearAdmin) ProtoMessage() {} +func (*MsgClearAdmin) Descriptor() ([]byte, []int) { + return fileDescriptor_22c4d58a052e9e95, []int{5} +} +func (m *MsgClearAdmin) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgClearAdmin) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgClearAdmin.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgClearAdmin) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgClearAdmin.Merge(m, src) +} +func (m *MsgClearAdmin) XXX_Size() int { + return m.Size() +} +func (m *MsgClearAdmin) XXX_DiscardUnknown() { + xxx_messageInfo_MsgClearAdmin.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgClearAdmin proto.InternalMessageInfo + +func init() { + proto.RegisterType((*MsgStoreCode)(nil), "wasmd.x.wasmd.v1beta1.MsgStoreCode") + proto.RegisterType((*MsgInstantiateContract)(nil), "wasmd.x.wasmd.v1beta1.MsgInstantiateContract") + proto.RegisterType((*MsgExecuteContract)(nil), "wasmd.x.wasmd.v1beta1.MsgExecuteContract") + proto.RegisterType((*MsgMigrateContract)(nil), "wasmd.x.wasmd.v1beta1.MsgMigrateContract") + proto.RegisterType((*MsgUpdateAdmin)(nil), "wasmd.x.wasmd.v1beta1.MsgUpdateAdmin") + proto.RegisterType((*MsgClearAdmin)(nil), "wasmd.x.wasmd.v1beta1.MsgClearAdmin") +} + +func init() { proto.RegisterFile("x/wasm/internal/types/msg.proto", fileDescriptor_22c4d58a052e9e95) } + +var fileDescriptor_22c4d58a052e9e95 = []byte{ + // 665 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xd4, 0x95, 0xbf, 0x6f, 0xd3, 0x40, + 0x14, 0xc7, 0xe3, 0xfc, 0x6a, 0x7b, 0x0d, 0x15, 0xb2, 0xda, 0xca, 0x54, 0xc8, 0x0e, 0xed, 0x92, + 0xa5, 0x76, 0x5b, 0x24, 0x90, 0x90, 0x18, 0x92, 0xf0, 0x43, 0x41, 0x32, 0x42, 0xae, 0x50, 0x05, + 0x4b, 0x74, 0xb6, 0xaf, 0xc7, 0x95, 0xf8, 0xae, 0xf2, 0xbb, 0x90, 0x74, 0x63, 0x64, 0x44, 0x4c, + 0x8c, 0x0c, 0x4c, 0x2c, 0xfc, 0x1b, 0x1d, 0x3b, 0x32, 0x05, 0x94, 0xfe, 0x17, 0x9d, 0xd0, 0xd9, + 0xd7, 0x2a, 0x48, 0x1d, 0xa2, 0xb6, 0x19, 0x58, 0x72, 0x39, 0xbd, 0xef, 0xfb, 0xbe, 0xe7, 0xcf, + 0xdd, 0xe9, 0x21, 0x67, 0xe8, 0x0d, 0x30, 0x24, 0x1e, 0xe3, 0x92, 0xa4, 0x1c, 0xf7, 0x3c, 0x79, + 0x74, 0x48, 0xc0, 0x4b, 0x80, 0xba, 0x87, 0xa9, 0x90, 0xc2, 0x5c, 0x51, 0xe1, 0xd8, 0x1d, 0xba, + 0xf9, 0xfa, 0x61, 0x3b, 0x24, 0x12, 0x6f, 0xaf, 0x2d, 0x53, 0x41, 0x45, 0xa6, 0xf0, 0xd4, 0xbf, + 0x5c, 0xbc, 0x66, 0x47, 0x02, 0x12, 0x01, 0x5e, 0x88, 0x81, 0x78, 0x5a, 0xea, 0x45, 0x82, 0x71, + 0x1d, 0xbf, 0x77, 0x79, 0xb5, 0xec, 0x37, 0x97, 0xac, 0x7f, 0x2f, 0xa2, 0x9a, 0x0f, 0x74, 0x57, + 0x8a, 0x94, 0xb4, 0x45, 0x4c, 0xcc, 0x0e, 0xaa, 0x02, 0xe1, 0x31, 0x49, 0x2d, 0xa3, 0x6e, 0x34, + 0x6a, 0xad, 0xed, 0xb3, 0x91, 0xb3, 0x49, 0x99, 0x7c, 0xd7, 0x0f, 0xdd, 0x48, 0x24, 0x9e, 0x2e, + 0x99, 0x2f, 0x9b, 0x10, 0xbf, 0xd7, 0x76, 0xcd, 0x28, 0x6a, 0xc6, 0x71, 0x4a, 0x00, 0x02, 0x6d, + 0x60, 0x3e, 0x40, 0x4b, 0xaa, 0x7c, 0x37, 0x3c, 0x92, 0xa4, 0x1b, 0x89, 0x98, 0x58, 0xc5, 0xcc, + 0xf2, 0xf6, 0x78, 0xe4, 0xd4, 0xf6, 0x9a, 0xbb, 0x7e, 0xeb, 0x48, 0x66, 0x45, 0x83, 0x9a, 0xd2, + 0x9d, 0xef, 0xcc, 0x55, 0x54, 0x05, 0xd1, 0x4f, 0x23, 0x62, 0x95, 0xea, 0x46, 0x63, 0x21, 0xd0, + 0x3b, 0xd3, 0x42, 0x73, 0x61, 0x9f, 0xf5, 0x54, 0x6f, 0xe5, 0x2c, 0x70, 0xbe, 0x35, 0xdf, 0xa0, + 0x95, 0x0e, 0x07, 0x89, 0xb9, 0x64, 0x58, 0x92, 0x57, 0x24, 0x4d, 0x18, 0x00, 0x13, 0xdc, 0xaa, + 0xd4, 0x8d, 0xc6, 0xe2, 0xce, 0x86, 0x7b, 0x29, 0x55, 0xd5, 0x33, 0x01, 0x68, 0x0b, 0xbe, 0xcf, + 0x68, 0x70, 0xb9, 0xc3, 0xa3, 0xf2, 0xa7, 0x6f, 0x4e, 0x61, 0xfd, 0x4b, 0x09, 0xad, 0xfa, 0x40, + 0x27, 0x24, 0x6d, 0xc1, 0x65, 0x8a, 0x23, 0x79, 0x93, 0xc0, 0x9e, 0xa3, 0x0a, 0x8e, 0x13, 0xc6, + 0x35, 0xa7, 0x2b, 0x38, 0xe5, 0xf9, 0xe6, 0x06, 0x9a, 0x53, 0xbc, 0xbb, 0x2c, 0xce, 0x10, 0x96, + 0x5b, 0x68, 0x3c, 0x72, 0xaa, 0x0a, 0x6e, 0xe7, 0x49, 0x50, 0x55, 0xa1, 0x4e, 0x6c, 0x2e, 0xa3, + 0x4a, 0x0f, 0x87, 0xa4, 0xa7, 0x61, 0xe6, 0x1b, 0xf3, 0x21, 0x9a, 0x67, 0x9c, 0xc9, 0x6e, 0x02, + 0x34, 0xa3, 0x57, 0x6b, 0xdd, 0x3d, 0x1b, 0x39, 0x16, 0xe1, 0x91, 0x88, 0x19, 0xa7, 0xde, 0x01, + 0x08, 0xee, 0x06, 0x78, 0xe0, 0x13, 0x00, 0x4c, 0x49, 0x30, 0xa7, 0xd4, 0x3e, 0x50, 0xf3, 0x00, + 0xa1, 0x2c, 0x71, 0xbf, 0xcf, 0x63, 0xb0, 0xaa, 0xf5, 0x52, 0x63, 0x71, 0xe7, 0x8e, 0x9b, 0x37, + 0xeb, 0xaa, 0x1b, 0x7a, 0x81, 0xbd, 0x2d, 0x18, 0x6f, 0x6d, 0x1d, 0x8f, 0x9c, 0xc2, 0x8f, 0xdf, + 0x4e, 0x63, 0x8a, 0x0f, 0x54, 0x09, 0x10, 0x2c, 0x28, 0xfb, 0x67, 0xca, 0x5d, 0x1f, 0xca, 0x49, + 0x11, 0x99, 0x3e, 0xd0, 0xa7, 0x43, 0x12, 0xf5, 0x67, 0x73, 0x20, 0x3e, 0x9a, 0x8f, 0xb4, 0xed, + 0xd5, 0xcf, 0xe4, 0xc2, 0xc2, 0x74, 0x51, 0x49, 0x61, 0x2d, 0x4d, 0x81, 0x55, 0x09, 0x15, 0x52, + 0x20, 0xfc, 0x1c, 0x69, 0x65, 0x06, 0x48, 0x95, 0xfd, 0x24, 0xd2, 0xaf, 0x39, 0x52, 0x9f, 0xd1, + 0x14, 0xff, 0x17, 0x48, 0xa7, 0xba, 0xe9, 0x8f, 0xd1, 0x62, 0x92, 0x7f, 0x51, 0x76, 0xad, 0xcb, + 0x53, 0xf0, 0x47, 0x3a, 0xc1, 0x07, 0xaa, 0xd1, 0x7c, 0x2c, 0xa2, 0x25, 0x1f, 0xe8, 0xeb, 0xc3, + 0x18, 0x4b, 0xd2, 0xcc, 0x9e, 0xd9, 0x0d, 0x62, 0x79, 0x89, 0x16, 0x38, 0x19, 0x74, 0xaf, 0xf9, + 0xfc, 0xe7, 0x39, 0x19, 0xe4, 0xad, 0x4d, 0x62, 0x2e, 0x5d, 0x1b, 0xb3, 0x46, 0xf0, 0xd3, 0x40, + 0xb7, 0x7c, 0xa0, 0xed, 0x1e, 0xc1, 0xe9, 0x8d, 0x13, 0x98, 0x45, 0xc7, 0xad, 0x17, 0xc7, 0x63, + 0xdb, 0x38, 0x19, 0xdb, 0xc6, 0x9f, 0xb1, 0x6d, 0x7c, 0x3e, 0xb5, 0x0b, 0x27, 0xa7, 0x76, 0xe1, + 0xd7, 0xa9, 0x5d, 0x78, 0xbb, 0x35, 0x61, 0xdc, 0x16, 0x90, 0xec, 0xa9, 0x41, 0x99, 0x8d, 0x07, + 0x6f, 0xa8, 0xd7, 0x7f, 0xc7, 0x66, 0x58, 0xcd, 0x26, 0xe6, 0xfd, 0xbf, 0x01, 0x00, 0x00, 0xff, + 0xff, 0xe0, 0x80, 0xf0, 0x2b, 0xc4, 0x07, 0x00, 0x00, +} + +func (m *MsgStoreCode) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgStoreCode) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgStoreCode) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.InstantiatePermission != nil { + { + size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMsg(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if len(m.Builder) > 0 { + i -= len(m.Builder) + copy(dAtA[i:], m.Builder) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Builder))) + i-- + dAtA[i] = 0x22 + } + if len(m.Source) > 0 { + i -= len(m.Source) + copy(dAtA[i:], m.Source) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Source))) + i-- + dAtA[i] = 0x1a + } + if len(m.WASMByteCode) > 0 { + i -= len(m.WASMByteCode) + copy(dAtA[i:], m.WASMByteCode) + i = encodeVarintMsg(dAtA, i, uint64(len(m.WASMByteCode))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgInstantiateContract) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgInstantiateContract) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgInstantiateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.InitFunds) > 0 { + for iNdEx := len(m.InitFunds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.InitFunds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMsg(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + } + } + if len(m.InitMsg) > 0 { + i -= len(m.InitMsg) + copy(dAtA[i:], m.InitMsg) + i = encodeVarintMsg(dAtA, i, uint64(len(m.InitMsg))) + i-- + dAtA[i] = 0x2a + } + if len(m.Label) > 0 { + i -= len(m.Label) + copy(dAtA[i:], m.Label) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Label))) + i-- + dAtA[i] = 0x22 + } + if m.CodeID != 0 { + i = encodeVarintMsg(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x18 + } + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgExecuteContract) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgExecuteContract) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgExecuteContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.SentFunds) > 0 { + for iNdEx := len(m.SentFunds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.SentFunds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintMsg(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + } + if len(m.Msg) > 0 { + i -= len(m.Msg) + copy(dAtA[i:], m.Msg) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Msg))) + i-- + dAtA[i] = 0x1a + } + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgMigrateContract) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgMigrateContract) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgMigrateContract) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MigrateMsg) > 0 { + i -= len(m.MigrateMsg) + copy(dAtA[i:], m.MigrateMsg) + i = encodeVarintMsg(dAtA, i, uint64(len(m.MigrateMsg))) + i-- + dAtA[i] = 0x22 + } + if m.CodeID != 0 { + i = encodeVarintMsg(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x18 + } + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgUpdateAdmin) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgUpdateAdmin) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgUpdateAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x1a + } + if len(m.NewAdmin) > 0 { + i -= len(m.NewAdmin) + copy(dAtA[i:], m.NewAdmin) + i = encodeVarintMsg(dAtA, i, uint64(len(m.NewAdmin))) + i-- + dAtA[i] = 0x12 + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgClearAdmin) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgClearAdmin) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgClearAdmin) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x1a + } + if len(m.Sender) > 0 { + i -= len(m.Sender) + copy(dAtA[i:], m.Sender) + i = encodeVarintMsg(dAtA, i, uint64(len(m.Sender))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintMsg(dAtA []byte, offset int, v uint64) int { + offset -= sovMsg(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *MsgStoreCode) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.WASMByteCode) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Source) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Builder) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + if m.InstantiatePermission != nil { + l = m.InstantiatePermission.Size() + n += 1 + l + sovMsg(uint64(l)) + } + return n +} + +func (m *MsgInstantiateContract) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + if m.CodeID != 0 { + n += 1 + sovMsg(uint64(m.CodeID)) + } + l = len(m.Label) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.InitMsg) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + if len(m.InitFunds) > 0 { + for _, e := range m.InitFunds { + l = e.Size() + n += 1 + l + sovMsg(uint64(l)) + } + } + return n +} + +func (m *MsgExecuteContract) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Msg) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + if len(m.SentFunds) > 0 { + for _, e := range m.SentFunds { + l = e.Size() + n += 1 + l + sovMsg(uint64(l)) + } + } + return n +} + +func (m *MsgMigrateContract) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + if m.CodeID != 0 { + n += 1 + sovMsg(uint64(m.CodeID)) + } + l = len(m.MigrateMsg) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + return n +} + +func (m *MsgUpdateAdmin) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.NewAdmin) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + return n +} + +func (m *MsgClearAdmin) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Sender) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovMsg(uint64(l)) + } + return n +} + +func sovMsg(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozMsg(x uint64) (n int) { + return sovMsg(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *MsgStoreCode) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgStoreCode: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgStoreCode: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) + if m.WASMByteCode == nil { + m.WASMByteCode = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Source = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Builder = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.InstantiatePermission == nil { + m.InstantiatePermission = &AccessConfig{} + } + if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgInstantiateContract) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgInstantiateContract: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgInstantiateContract: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = append(m.Admin[:0], dAtA[iNdEx:postIndex]...) + if m.Admin == nil { + m.Admin = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Label = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitMsg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitMsg = append(m.InitMsg[:0], dAtA[iNdEx:postIndex]...) + if m.InitMsg == nil { + m.InitMsg = []byte{} + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitFunds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitFunds = append(m.InitFunds, types.Coin{}) + if err := m.InitFunds[len(m.InitFunds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgExecuteContract) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgExecuteContract: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgExecuteContract: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) + if m.Msg == nil { + m.Msg = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field SentFunds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.SentFunds = append(m.SentFunds, types.Coin{}) + if err := m.SentFunds[len(m.SentFunds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgMigrateContract) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgMigrateContract: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgMigrateContract: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MigrateMsg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MigrateMsg = append(m.MigrateMsg[:0], dAtA[iNdEx:postIndex]...) + if m.MigrateMsg == nil { + m.MigrateMsg = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgUpdateAdmin) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgUpdateAdmin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgUpdateAdmin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NewAdmin = append(m.NewAdmin[:0], dAtA[iNdEx:postIndex]...) + if m.NewAdmin == nil { + m.NewAdmin = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgClearAdmin) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgClearAdmin: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgClearAdmin: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Sender", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Sender = append(m.Sender[:0], dAtA[iNdEx:postIndex]...) + if m.Sender == nil { + m.Sender = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowMsg + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthMsg + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthMsg + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipMsg(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthMsg + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipMsg(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowMsg + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowMsg + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowMsg + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthMsg + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupMsg + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthMsg + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthMsg = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowMsg = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupMsg = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/wasm/internal/types/msg.proto b/x/wasm/internal/types/msg.proto new file mode 100644 index 0000000000..bc041314e9 --- /dev/null +++ b/x/wasm/internal/types/msg.proto @@ -0,0 +1,69 @@ +syntax = "proto3"; +package wasmd.x.wasmd.v1beta1; + +option go_package = "github.com/CosmWasm/wasmd/x/wasmd/internal/types"; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; + +import "x/wasm/internal/types/types.proto"; + + +message MsgStoreCode { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + // WASMByteCode can be raw or gzip compressed + bytes wasm_byte_code = 2 [(gogoproto.customname) = "WASMByteCode"]; + // Source is a valid absolute HTTPS URI to the contract's source code, optional + string source = 3; + // Builder is a valid docker image name with tag, optional + string builder = 4; + // InstantiatePermission to apply on contract creation, optional + AccessConfig InstantiatePermission = 5; +} + +message MsgInstantiateContract { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + // Admin is an optional address that can execute migrations + bytes admin = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + uint64 code_id = 3 [(gogoproto.customname) = "CodeID"]; + string label = 4; + bytes init_msg = 5 [(gogoproto.casttype) = "encoding/json.RawMessage"]; + repeated cosmos.base.v1beta1.Coin init_funds = 6 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; +} + +message MsgExecuteContract { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes contract = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes msg = 3 [(gogoproto.casttype) = "encoding/json.RawMessage"]; + repeated cosmos.base.v1beta1.Coin sent_funds = 5 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; +} + +message MsgMigrateContract { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes contract = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + uint64 code_id = 3 [(gogoproto.customname) = "CodeID"]; + bytes migrate_msg = 4 [(gogoproto.casttype) = "encoding/json.RawMessage"]; +} + +message MsgUpdateAdmin { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes new_admin = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes contract = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} + +message MsgClearAdmin { + option (gogoproto.goproto_getters) = false; + + bytes sender = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes contract = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} diff --git a/x/wasm/internal/types/msg_test.go b/x/wasm/internal/types/msg_test.go index 038bae48f5..439b0c713e 100644 --- a/x/wasm/internal/types/msg_test.go +++ b/x/wasm/internal/types/msg_test.go @@ -113,7 +113,7 @@ func TestStoreCodeValidation(t *testing.T) { msg: MsgStoreCode{ Sender: goodAddress, WASMByteCode: []byte("foo"), - InstantiatePermission: &AccessConfig{Type: OnlyAddress, Address: badAddress}, + InstantiatePermission: &AccessConfig{Permission: AccessTypeOnlyAddress, Address: badAddress}, }, valid: false, }, diff --git a/x/wasm/internal/types/params.go b/x/wasm/internal/types/params.go index 86de2a1e0e..5c801279f2 100644 --- a/x/wasm/internal/types/params.go +++ b/x/wasm/internal/types/params.go @@ -1,11 +1,13 @@ package types import ( + "encoding/json" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - "github.com/cosmos/cosmos-sdk/x/params" + paramtypes "github.com/cosmos/cosmos-sdk/x/params/types" + "github.com/gogo/protobuf/jsonpb" "github.com/pkg/errors" "gopkg.in/yaml.v2" ) @@ -18,84 +20,81 @@ const ( var ParamStoreKeyUploadAccess = []byte("uploadAccess") var ParamStoreKeyInstantiateAccess = []byte("instantiateAccess") -type AccessType string - -const ( - Undefined AccessType = "Undefined" - Nobody AccessType = "Nobody" - OnlyAddress AccessType = "OnlyAddress" - Everybody AccessType = "Everybody" -) - -var AllAccessTypes = map[AccessType]struct{}{ - Nobody: {}, - OnlyAddress: {}, - Everybody: {}, +var AllAccessTypes = []AccessType{ + AccessTypeNobody, + AccessTypeOnlyAddress, + AccessTypeEverybody, } func (a AccessType) With(addr sdk.AccAddress) AccessConfig { switch a { - case Nobody: + case AccessTypeNobody: return AllowNobody - case OnlyAddress: + case AccessTypeOnlyAddress: if err := sdk.VerifyAddressFormat(addr); err != nil { panic(err) } - return AccessConfig{Type: OnlyAddress, Address: addr} - case Everybody: + return AccessConfig{Permission: AccessTypeOnlyAddress, Address: addr} + case AccessTypeEverybody: return AllowEverybody } panic("unsupported access type") } +func (a AccessType) String() string { + switch a { + case AccessTypeNobody: + return "Nobody" + case AccessTypeOnlyAddress: + return "OnlyAddress" + case AccessTypeEverybody: + return "Everybody" + } + return "Undefined" +} + func (a *AccessType) UnmarshalText(text []byte) error { - s := AccessType(text) - if _, ok := AllAccessTypes[s]; ok { - *a = s - return nil + for _, v := range AllAccessTypes { + if v.String() == string(text) { + *a = v + return nil + } } - *a = Undefined + *a = AccessTypeUndefined return nil } - func (a AccessType) MarshalText() ([]byte, error) { - if _, ok := AllAccessTypes[a]; ok { - return []byte(a), nil - } - return []byte(Undefined), nil + return []byte(a.String()), nil +} + +func (a *AccessType) MarshalJSONPB(_ *jsonpb.Marshaler) ([]byte, error) { + return json.Marshal(a) } -type AccessConfig struct { - Type AccessType `json:"permission" yaml:"permission"` - Address sdk.AccAddress `json:"address,omitempty" yaml:"address"` +func (a *AccessType) UnmarshalJSONPB(_ *jsonpb.Unmarshaler, data []byte) error { + return json.Unmarshal(data, a) } func (a AccessConfig) Equals(o AccessConfig) bool { - return a.Type == o.Type && a.Address.Equals(o.Address) + return a.Permission == o.Permission && a.Address.Equals(o.Address) } var ( DefaultUploadAccess = AllowEverybody - AllowEverybody = AccessConfig{Type: Everybody} - AllowNobody = AccessConfig{Type: Nobody} + AllowEverybody = AccessConfig{Permission: AccessTypeEverybody} + AllowNobody = AccessConfig{Permission: AccessTypeNobody} ) -// Params defines the set of wasm parameters. -type Params struct { - UploadAccess AccessConfig `json:"code_upload_access" yaml:"code_upload_access"` - DefaultInstantiatePermission AccessType `json:"instantiate_default_permission" yaml:"instantiate_default_permission"` -} - // ParamKeyTable returns the parameter key table. -func ParamKeyTable() params.KeyTable { - return params.NewKeyTable().RegisterParamSet(&Params{}) +func ParamKeyTable() paramtypes.KeyTable { + return paramtypes.NewKeyTable().RegisterParamSet(&Params{}) } // DefaultParams returns default wasm parameters func DefaultParams() Params { return Params{ - UploadAccess: AllowEverybody, - DefaultInstantiatePermission: Everybody, + CodeUploadAccess: AllowEverybody, + InstantiateDefaultPermission: AccessTypeEverybody, } } @@ -105,19 +104,19 @@ func (p Params) String() string { } // ParamSetPairs returns the parameter set pairs. -func (p *Params) ParamSetPairs() params.ParamSetPairs { - return params.ParamSetPairs{ - params.NewParamSetPair(ParamStoreKeyUploadAccess, &p.UploadAccess, validateAccessConfig), - params.NewParamSetPair(ParamStoreKeyInstantiateAccess, &p.DefaultInstantiatePermission, validateAccessType), +func (p *Params) ParamSetPairs() paramtypes.ParamSetPairs { + return paramtypes.ParamSetPairs{ + paramtypes.NewParamSetPair(ParamStoreKeyUploadAccess, &p.CodeUploadAccess, validateAccessConfig), + paramtypes.NewParamSetPair(ParamStoreKeyInstantiateAccess, &p.InstantiateDefaultPermission, validateAccessType), } } // ValidateBasic performs basic validation on wasm parameters func (p Params) ValidateBasic() error { - if err := validateAccessType(p.DefaultInstantiatePermission); err != nil { + if err := validateAccessType(p.InstantiateDefaultPermission); err != nil { return errors.Wrap(err, "instantiate default permission") } - if err := validateAccessConfig(p.UploadAccess); err != nil { + if err := validateAccessConfig(p.CodeUploadAccess); err != nil { return errors.Wrap(err, "upload access") } return nil @@ -132,41 +131,43 @@ func validateAccessConfig(i interface{}) error { } func validateAccessType(i interface{}) error { - v, ok := i.(AccessType) + a, ok := i.(AccessType) if !ok { return fmt.Errorf("invalid parameter type: %T", i) } - if v == Undefined { + if a == AccessTypeUndefined { return sdkerrors.Wrap(ErrEmpty, "type") } - if _, ok := AllAccessTypes[v]; !ok { - return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", v) + for _, v := range AllAccessTypes { + if v == a { + return nil + } } - return nil + return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", a) } func (v AccessConfig) ValidateBasic() error { - switch v.Type { - case Undefined, "": + switch v.Permission { + case AccessTypeUndefined: return sdkerrors.Wrap(ErrEmpty, "type") - case Nobody, Everybody: + case AccessTypeNobody, AccessTypeEverybody: if len(v.Address) != 0 { return sdkerrors.Wrap(ErrInvalid, "address not allowed for this type") } return nil - case OnlyAddress: + case AccessTypeOnlyAddress: return sdk.VerifyAddressFormat(v.Address) } - return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", v.Type) + return sdkerrors.Wrapf(ErrInvalid, "unknown type: %q", v.Permission) } func (v AccessConfig) Allowed(actor sdk.AccAddress) bool { - switch v.Type { - case Nobody: + switch v.Permission { + case AccessTypeNobody: return false - case Everybody: + case AccessTypeEverybody: return true - case OnlyAddress: + case AccessTypeOnlyAddress: return v.Address.Equals(actor) default: panic("unknown type") diff --git a/x/wasm/internal/types/params_test.go b/x/wasm/internal/types/params_test.go index 0c78b148da..dabf6f306c 100644 --- a/x/wasm/internal/types/params_test.go +++ b/x/wasm/internal/types/params_test.go @@ -24,66 +24,65 @@ func TestValidateParams(t *testing.T) { }, "all good with nobody": { src: Params{ - UploadAccess: AllowNobody, - DefaultInstantiatePermission: Nobody, + CodeUploadAccess: AllowNobody, + InstantiateDefaultPermission: AccessTypeNobody, }, }, "all good with everybody": { src: Params{ - UploadAccess: AllowEverybody, - DefaultInstantiatePermission: Everybody, + CodeUploadAccess: AllowEverybody, + InstantiateDefaultPermission: AccessTypeEverybody, }, }, "all good with only address": { src: Params{ - UploadAccess: OnlyAddress.With(anyAddress), - DefaultInstantiatePermission: OnlyAddress, + CodeUploadAccess: AccessTypeOnlyAddress.With(anyAddress), + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, }, "reject empty type in instantiate permission": { src: Params{ - UploadAccess: AllowNobody, - DefaultInstantiatePermission: "", + CodeUploadAccess: AllowNobody, }, expErr: true, }, "reject unknown type in instantiate": { src: Params{ - UploadAccess: AllowNobody, - DefaultInstantiatePermission: "Undefined", + CodeUploadAccess: AllowNobody, + InstantiateDefaultPermission: 1111, }, expErr: true, }, "reject invalid address in only address": { src: Params{ - UploadAccess: AccessConfig{Type: OnlyAddress, Address: invalidAddress}, - DefaultInstantiatePermission: OnlyAddress, + CodeUploadAccess: AccessConfig{Permission: AccessTypeOnlyAddress, Address: invalidAddress}, + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, expErr: true, }, - "reject UploadAccess Everybody with obsolete address": { + "reject CodeUploadAccess Everybody with obsolete address": { src: Params{ - UploadAccess: AccessConfig{Type: Everybody, Address: anyAddress}, - DefaultInstantiatePermission: OnlyAddress, + CodeUploadAccess: AccessConfig{Permission: AccessTypeEverybody, Address: anyAddress}, + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, expErr: true, }, - "reject UploadAccess Nobody with obsolete address": { + "reject CodeUploadAccess Nobody with obsolete address": { src: Params{ - UploadAccess: AccessConfig{Type: Nobody, Address: anyAddress}, - DefaultInstantiatePermission: OnlyAddress, + CodeUploadAccess: AccessConfig{Permission: AccessTypeNobody, Address: anyAddress}, + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, expErr: true, }, - "reject empty UploadAccess": { + "reject empty CodeUploadAccess": { src: Params{ - DefaultInstantiatePermission: OnlyAddress, + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, expErr: true, - }, "reject undefined permission in UploadAccess": { + }, "reject undefined permission in CodeUploadAccess": { src: Params{ - UploadAccess: AccessConfig{Type: Undefined}, - DefaultInstantiatePermission: OnlyAddress, + CodeUploadAccess: AccessConfig{Permission: AccessTypeUndefined}, + InstantiateDefaultPermission: AccessTypeOnlyAddress, }, expErr: true, }, @@ -105,11 +104,11 @@ func TestAccessTypeMarshalJson(t *testing.T) { src AccessType exp string }{ - "Undefined": {src: Undefined, exp: `"Undefined"`}, - "Nobody": {src: Nobody, exp: `"Nobody"`}, - "OnlyAddress": {src: OnlyAddress, exp: `"OnlyAddress"`}, - "Everybody": {src: Everybody, exp: `"Everybody"`}, - "unknown": {src: "", exp: `"Undefined"`}, + "Undefined": {src: AccessTypeUndefined, exp: `"Undefined"`}, + "Nobody": {src: AccessTypeNobody, exp: `"Nobody"`}, + "OnlyAddress": {src: AccessTypeOnlyAddress, exp: `"OnlyAddress"`}, + "Everybody": {src: AccessTypeEverybody, exp: `"Everybody"`}, + "unknown": {src: 999, exp: `"Undefined"`}, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { @@ -119,16 +118,17 @@ func TestAccessTypeMarshalJson(t *testing.T) { }) } } -func TestAccessTypeUnMarshalJson(t *testing.T) { + +func TestAccessTypeUnmarshalJson(t *testing.T) { specs := map[string]struct { src string exp AccessType }{ - "Undefined": {src: `"Undefined"`, exp: Undefined}, - "Nobody": {src: `"Nobody"`, exp: Nobody}, - "OnlyAddress": {src: `"OnlyAddress"`, exp: OnlyAddress}, - "Everybody": {src: `"Everybody"`, exp: Everybody}, - "unknown": {src: `""`, exp: Undefined}, + "Undefined": {src: `"Undefined"`, exp: AccessTypeUndefined}, + "Nobody": {src: `"Nobody"`, exp: AccessTypeNobody}, + "OnlyAddress": {src: `"OnlyAddress"`, exp: AccessTypeOnlyAddress}, + "Everybody": {src: `"Everybody"`, exp: AccessTypeEverybody}, + "unknown": {src: `""`, exp: AccessTypeUndefined}, } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { @@ -139,3 +139,24 @@ func TestAccessTypeUnMarshalJson(t *testing.T) { }) } } +func TestParamsUnmarshalJson(t *testing.T) { + specs := map[string]struct { + src string + exp Params + }{ + + "defaults": { + src: `{"code_upload_access": {"permission": "Everybody"}, + "instantiate_default_permission": "Everybody"}`, + exp: DefaultParams(), + }, + } + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + var val Params + err := ModuleCdc.UnmarshalJSON([]byte(spec.src), &val) + require.NoError(t, err) + assert.Equal(t, spec.exp, val) + }) + } +} diff --git a/x/wasm/internal/types/proposal.go b/x/wasm/internal/types/proposal.go index 23a35ebb82..dfd14d85c4 100644 --- a/x/wasm/internal/types/proposal.go +++ b/x/wasm/internal/types/proposal.go @@ -2,7 +2,6 @@ package types import ( "encoding/base64" - "encoding/json" "fmt" "strings" @@ -64,65 +63,21 @@ func init() { // register new content types with the sdk govtypes.RegisterProposalTypeCodec(ClearAdminProposal{}, "wasm/ClearAdminProposal") } -// WasmProposal contains common proposal data. -type WasmProposal struct { - Title string `json:"title" yaml:"title"` - Description string `json:"description" yaml:"description"` -} - -// GetTitle returns the title of a parameter change proposal. -func (p WasmProposal) GetTitle() string { return p.Title } - -// GetDescription returns the description of a parameter change proposal. -func (p WasmProposal) GetDescription() string { return p.Description } - // ProposalRoute returns the routing key of a parameter change proposal. -func (p WasmProposal) ProposalRoute() string { return RouterKey } +func (p StoreCodeProposal) ProposalRoute() string { return RouterKey } -// ValidateBasic validates the proposal -func (p WasmProposal) ValidateBasic() error { - if strings.TrimSpace(p.Title) != p.Title { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") - } - if len(p.Title) == 0 { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") - } - if len(p.Title) > govtypes.MaxTitleLength { - return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal title is longer than max length of %d", govtypes.MaxTitleLength) - } - if strings.TrimSpace(p.Description) != p.Description { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") - } - if len(p.Description) == 0 { - return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") - } - if len(p.Description) > govtypes.MaxDescriptionLength { - return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", govtypes.MaxDescriptionLength) - } - return nil -} +// GetTitle returns the title of the proposal +func (p *StoreCodeProposal) GetTitle() string { return p.Title } -// StoreCodeProposal gov proposal content type to store wasm code. -type StoreCodeProposal struct { - WasmProposal - // RunAs is the address that "owns" the code object - RunAs sdk.AccAddress `json:"run_as"` - // WASMByteCode can be raw or gzip compressed - WASMByteCode []byte `json:"wasm_byte_code"` - // Source is a valid absolute HTTPS URI to the contract's source code, optional - Source string `json:"source"` - // Builder is a valid docker image name with tag, optional - Builder string `json:"builder"` - // InstantiatePermission to apply on contract creation, optional - InstantiatePermission *AccessConfig `json:"instantiate_permission"` -} +// GetDescription returns the human readable description of the proposal +func (p StoreCodeProposal) GetDescription() string { return p.Description } // ProposalType returns the type func (p StoreCodeProposal) ProposalType() string { return string(ProposalTypeStoreCode) } // ValidateBasic validates the proposal func (p StoreCodeProposal) ValidateBasic() error { - if err := p.WasmProposal.ValidateBasic(); err != nil { + if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } if err := sdk.VerifyAddressFormat(p.RunAs); err != nil { @@ -160,16 +115,19 @@ func (p StoreCodeProposal) String() string { `, p.Title, p.Description, p.RunAs, p.WASMByteCode, p.Source, p.Builder) } +// MarshalYAML pretty prints the wasm byte code func (p StoreCodeProposal) MarshalYAML() (interface{}, error) { return struct { - WasmProposal `yaml:",inline"` + Title string `yaml:"title"` + Description string `yaml:"description"` RunAs sdk.AccAddress `yaml:"run_as"` WASMByteCode string `yaml:"wasm_byte_code"` Source string `yaml:"source"` Builder string `yaml:"builder"` InstantiatePermission *AccessConfig `yaml:"instantiate_permission"` }{ - WasmProposal: p.WasmProposal, + Title: p.Title, + Description: p.Description, RunAs: p.RunAs, WASMByteCode: base64.StdEncoding.EncodeToString(p.WASMByteCode), Source: p.Source, @@ -178,18 +136,14 @@ func (p StoreCodeProposal) MarshalYAML() (interface{}, error) { }, nil } -// InstantiateContractProposal gov proposal content type to instantiate a contract. -type InstantiateContractProposal struct { - WasmProposal - // RunAs is the address that pays the init funds - RunAs sdk.AccAddress `json:"run_as"` - // Admin is an optional address that can execute migrations - Admin sdk.AccAddress `json:"admin,omitempty"` - CodeID uint64 `json:"code_id"` - Label string `json:"label"` - InitMsg json.RawMessage `json:"init_msg"` - InitFunds sdk.Coins `json:"init_funds"` -} +// ProposalRoute returns the routing key of a parameter change proposal. +func (p InstantiateContractProposal) ProposalRoute() string { return RouterKey } + +// GetTitle returns the title of the proposal +func (p *InstantiateContractProposal) GetTitle() string { return p.Title } + +// GetDescription returns the human readable description of the proposal +func (p InstantiateContractProposal) GetDescription() string { return p.Description } // ProposalType returns the type func (p InstantiateContractProposal) ProposalType() string { @@ -198,7 +152,7 @@ func (p InstantiateContractProposal) ProposalType() string { // ValidateBasic validates the proposal func (p InstantiateContractProposal) ValidateBasic() error { - if err := p.WasmProposal.ValidateBasic(); err != nil { + if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } if err := sdk.VerifyAddressFormat(p.RunAs); err != nil { @@ -240,42 +194,44 @@ func (p InstantiateContractProposal) String() string { `, p.Title, p.Description, p.RunAs, p.Admin, p.CodeID, p.Label, p.InitMsg, p.InitFunds) } +// MarshalYAML pretty prints the init message func (p InstantiateContractProposal) MarshalYAML() (interface{}, error) { return struct { - WasmProposal `yaml:",inline"` - RunAs sdk.AccAddress `yaml:"run_as"` - Admin sdk.AccAddress `yaml:"admin"` - CodeID uint64 `yaml:"code_id"` - Label string `yaml:"label"` - InitMsg string `yaml:"init_msg"` - InitFunds sdk.Coins `yaml:"init_funds"` + Title string `yaml:"title"` + Description string `yaml:"description"` + RunAs sdk.AccAddress `yaml:"run_as"` + Admin sdk.AccAddress `yaml:"admin"` + CodeID uint64 `yaml:"code_id"` + Label string `yaml:"label"` + InitMsg string `yaml:"init_msg"` + InitFunds sdk.Coins `yaml:"init_funds"` }{ - WasmProposal: p.WasmProposal, - RunAs: p.RunAs, - Admin: p.Admin, - CodeID: p.CodeID, - Label: p.Label, - InitMsg: string(p.InitMsg), - InitFunds: p.InitFunds, + Title: p.Title, + Description: p.Description, + RunAs: p.RunAs, + Admin: p.Admin, + CodeID: p.CodeID, + Label: p.Label, + InitMsg: string(p.InitMsg), + InitFunds: p.InitFunds, }, nil } -// MigrateContractProposal gov proposal content type to migrate a contract. -type MigrateContractProposal struct { - WasmProposal `yaml:",inline"` - Contract sdk.AccAddress `json:"contract"` - CodeID uint64 `json:"code_id"` - MigrateMsg json.RawMessage `json:"msg"` - // RunAs is the address that is passed to the contract's environment as sender - RunAs sdk.AccAddress `json:"run_as"` -} +// ProposalRoute returns the routing key of a parameter change proposal. +func (p MigrateContractProposal) ProposalRoute() string { return RouterKey } + +// GetTitle returns the title of the proposal +func (p *MigrateContractProposal) GetTitle() string { return p.Title } + +// GetDescription returns the human readable description of the proposal +func (p MigrateContractProposal) GetDescription() string { return p.Description } // ProposalType returns the type func (p MigrateContractProposal) ProposalType() string { return string(ProposalTypeMigrateContract) } // ValidateBasic validates the proposal func (p MigrateContractProposal) ValidateBasic() error { - if err := p.WasmProposal.ValidateBasic(); err != nil { + if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } if p.CodeID == 0 { @@ -302,35 +258,40 @@ func (p MigrateContractProposal) String() string { `, p.Title, p.Description, p.Contract, p.CodeID, p.RunAs, p.MigrateMsg) } +// MarshalYAML pretty prints the migrate message func (p MigrateContractProposal) MarshalYAML() (interface{}, error) { return struct { - WasmProposal `yaml:",inline"` - Contract sdk.AccAddress `yaml:"contract"` - CodeID uint64 `yaml:"code_id"` - MigrateMsg string `yaml:"msg"` - RunAs sdk.AccAddress `yaml:"run_as"` + Title string `yaml:"title"` + Description string `yaml:"description"` + Contract sdk.AccAddress `yaml:"contract"` + CodeID uint64 `yaml:"code_id"` + MigrateMsg string `yaml:"msg"` + RunAs sdk.AccAddress `yaml:"run_as"` }{ - WasmProposal: p.WasmProposal, - Contract: p.Contract, - CodeID: p.CodeID, - MigrateMsg: string(p.MigrateMsg), - RunAs: p.RunAs, + Title: p.Title, + Description: p.Description, + Contract: p.Contract, + CodeID: p.CodeID, + MigrateMsg: string(p.MigrateMsg), + RunAs: p.RunAs, }, nil } -// UpdateAdminProposal gov proposal content type to set an admin for a contract. -type UpdateAdminProposal struct { - WasmProposal `yaml:",inline"` - NewAdmin sdk.AccAddress `json:"new_admin" yaml:"new_admin"` - Contract sdk.AccAddress `json:"contract" yaml:"contract"` -} +// ProposalRoute returns the routing key of a parameter change proposal. +func (p UpdateAdminProposal) ProposalRoute() string { return RouterKey } + +// GetTitle returns the title of the proposal +func (p *UpdateAdminProposal) GetTitle() string { return p.Title } + +// GetDescription returns the human readable description of the proposal +func (p UpdateAdminProposal) GetDescription() string { return p.Description } // ProposalType returns the type func (p UpdateAdminProposal) ProposalType() string { return string(ProposalTypeUpdateAdmin) } // ValidateBasic validates the proposal func (p UpdateAdminProposal) ValidateBasic() error { - if err := p.WasmProposal.ValidateBasic(); err != nil { + if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } if err := sdk.VerifyAddressFormat(p.Contract); err != nil { @@ -352,19 +313,21 @@ func (p UpdateAdminProposal) String() string { `, p.Title, p.Description, p.Contract, p.NewAdmin) } -// ClearAdminProposal gov proposal content type to clear the admin of a contract. -type ClearAdminProposal struct { - WasmProposal `yaml:",inline"` +// ProposalRoute returns the routing key of a parameter change proposal. +func (p ClearAdminProposal) ProposalRoute() string { return RouterKey } - Contract sdk.AccAddress `json:"contract" yaml:"contract"` -} +// GetTitle returns the title of the proposal +func (p *ClearAdminProposal) GetTitle() string { return p.Title } + +// GetDescription returns the human readable description of the proposal +func (p ClearAdminProposal) GetDescription() string { return p.Description } // ProposalType returns the type func (p ClearAdminProposal) ProposalType() string { return string(ProposalTypeClearAdmin) } // ValidateBasic validates the proposal func (p ClearAdminProposal) ValidateBasic() error { - if err := p.WasmProposal.ValidateBasic(); err != nil { + if err := validateProposalCommons(p.Title, p.Description); err != nil { return err } if err := sdk.VerifyAddressFormat(p.Contract); err != nil { @@ -381,3 +344,25 @@ func (p ClearAdminProposal) String() string { Contract: %s `, p.Title, p.Description, p.Contract) } + +func validateProposalCommons(title, description string) error { + if strings.TrimSpace(title) != title { + return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title must not start/end with white spaces") + } + if len(title) == 0 { + return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal title cannot be blank") + } + if len(title) > govtypes.MaxTitleLength { + return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal title is longer than max length of %d", govtypes.MaxTitleLength) + } + if strings.TrimSpace(description) != description { + return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description must not start/end with white spaces") + } + if len(description) == 0 { + return sdkerrors.Wrap(govtypes.ErrInvalidProposalContent, "proposal description cannot be blank") + } + if len(description) > govtypes.MaxDescriptionLength { + return sdkerrors.Wrapf(govtypes.ErrInvalidProposalContent, "proposal description is longer than max length of %d", govtypes.MaxDescriptionLength) + } + return nil +} diff --git a/x/wasm/internal/types/proposal.pb.go b/x/wasm/internal/types/proposal.pb.go new file mode 100644 index 0000000000..6c084e445f --- /dev/null +++ b/x/wasm/internal/types/proposal.pb.go @@ -0,0 +1,2237 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: x/wasm/internal/types/proposal.proto + +package types + +import ( + bytes "bytes" + encoding_json "encoding/json" + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type StoreCodeProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + // RunAs is the address that is passed to the contract's environment as sender + RunAs github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"run_as,omitempty"` + // WASMByteCode can be raw or gzip compressed + WASMByteCode []byte `protobuf:"bytes,4,opt,name=wasm_byte_code,json=wasmByteCode,proto3" json:"wasm_byte_code,omitempty"` + // Source is a valid absolute HTTPS URI to the contract's source code, optional + Source string `protobuf:"bytes,5,opt,name=source,proto3" json:"source,omitempty"` + // Builder is a valid docker image name with tag, optional + Builder string `protobuf:"bytes,6,opt,name=builder,proto3" json:"builder,omitempty"` + // InstantiatePermission to apply on contract creation, optional + InstantiatePermission *AccessConfig `protobuf:"bytes,7,opt,name=InstantiatePermission,proto3" json:"InstantiatePermission,omitempty"` +} + +func (m *StoreCodeProposal) Reset() { *m = StoreCodeProposal{} } +func (*StoreCodeProposal) ProtoMessage() {} +func (*StoreCodeProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_00b43267813130fb, []int{0} +} +func (m *StoreCodeProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *StoreCodeProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_StoreCodeProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *StoreCodeProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_StoreCodeProposal.Merge(m, src) +} +func (m *StoreCodeProposal) XXX_Size() int { + return m.Size() +} +func (m *StoreCodeProposal) XXX_DiscardUnknown() { + xxx_messageInfo_StoreCodeProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_StoreCodeProposal proto.InternalMessageInfo + +// InstantiateContractProposal gov proposal content type to instantiate a contract. +type InstantiateContractProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + // RunAs is the address that is passed to the contract's environment as sender + RunAs github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"run_as,omitempty"` + // Admin is an optional address that can execute migrations + Admin github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,opt,name=admin,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"admin,omitempty"` + CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + Label string `protobuf:"bytes,6,opt,name=label,proto3" json:"label,omitempty"` + InitMsg encoding_json.RawMessage `protobuf:"bytes,7,opt,name=init_msg,json=initMsg,proto3,casttype=encoding/json.RawMessage" json:"init_msg,omitempty"` + InitFunds github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,8,rep,name=init_funds,json=initFunds,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"init_funds"` +} + +func (m *InstantiateContractProposal) Reset() { *m = InstantiateContractProposal{} } +func (*InstantiateContractProposal) ProtoMessage() {} +func (*InstantiateContractProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_00b43267813130fb, []int{1} +} +func (m *InstantiateContractProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *InstantiateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_InstantiateContractProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *InstantiateContractProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_InstantiateContractProposal.Merge(m, src) +} +func (m *InstantiateContractProposal) XXX_Size() int { + return m.Size() +} +func (m *InstantiateContractProposal) XXX_DiscardUnknown() { + xxx_messageInfo_InstantiateContractProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_InstantiateContractProposal proto.InternalMessageInfo + +// MigrateContractProposal gov proposal content type to migrate a contract. +type MigrateContractProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + // RunAs is the address that is passed to the contract's environment as sender + RunAs github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=run_as,json=runAs,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"run_as,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` + CodeID uint64 `protobuf:"varint,5,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + MigrateMsg encoding_json.RawMessage `protobuf:"bytes,6,opt,name=migrate_msg,json=migrateMsg,proto3,casttype=encoding/json.RawMessage" json:"migrate_msg,omitempty"` +} + +func (m *MigrateContractProposal) Reset() { *m = MigrateContractProposal{} } +func (*MigrateContractProposal) ProtoMessage() {} +func (*MigrateContractProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_00b43267813130fb, []int{2} +} +func (m *MigrateContractProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MigrateContractProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MigrateContractProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MigrateContractProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_MigrateContractProposal.Merge(m, src) +} +func (m *MigrateContractProposal) XXX_Size() int { + return m.Size() +} +func (m *MigrateContractProposal) XXX_DiscardUnknown() { + xxx_messageInfo_MigrateContractProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_MigrateContractProposal proto.InternalMessageInfo + +// UpdateAdminProposal gov proposal content type to set an admin for a contract. +type UpdateAdminProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + NewAdmin github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=new_admin,json=newAdmin,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"new_admin,omitempty" yaml:"new_admin"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,4,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` +} + +func (m *UpdateAdminProposal) Reset() { *m = UpdateAdminProposal{} } +func (*UpdateAdminProposal) ProtoMessage() {} +func (*UpdateAdminProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_00b43267813130fb, []int{3} +} +func (m *UpdateAdminProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *UpdateAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_UpdateAdminProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *UpdateAdminProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_UpdateAdminProposal.Merge(m, src) +} +func (m *UpdateAdminProposal) XXX_Size() int { + return m.Size() +} +func (m *UpdateAdminProposal) XXX_DiscardUnknown() { + xxx_messageInfo_UpdateAdminProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_UpdateAdminProposal proto.InternalMessageInfo + +// ClearAdminProposal gov proposal content type to clear the admin of a contract. +type ClearAdminProposal struct { + Title string `protobuf:"bytes,1,opt,name=title,proto3" json:"title,omitempty"` + Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"` + Contract github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=contract,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"contract,omitempty"` +} + +func (m *ClearAdminProposal) Reset() { *m = ClearAdminProposal{} } +func (*ClearAdminProposal) ProtoMessage() {} +func (*ClearAdminProposal) Descriptor() ([]byte, []int) { + return fileDescriptor_00b43267813130fb, []int{4} +} +func (m *ClearAdminProposal) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ClearAdminProposal) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ClearAdminProposal.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ClearAdminProposal) XXX_Merge(src proto.Message) { + xxx_messageInfo_ClearAdminProposal.Merge(m, src) +} +func (m *ClearAdminProposal) XXX_Size() int { + return m.Size() +} +func (m *ClearAdminProposal) XXX_DiscardUnknown() { + xxx_messageInfo_ClearAdminProposal.DiscardUnknown(m) +} + +var xxx_messageInfo_ClearAdminProposal proto.InternalMessageInfo + +func init() { + proto.RegisterType((*StoreCodeProposal)(nil), "wasmd.x.wasmd.v1beta1.StoreCodeProposal") + proto.RegisterType((*InstantiateContractProposal)(nil), "wasmd.x.wasmd.v1beta1.InstantiateContractProposal") + proto.RegisterType((*MigrateContractProposal)(nil), "wasmd.x.wasmd.v1beta1.MigrateContractProposal") + proto.RegisterType((*UpdateAdminProposal)(nil), "wasmd.x.wasmd.v1beta1.UpdateAdminProposal") + proto.RegisterType((*ClearAdminProposal)(nil), "wasmd.x.wasmd.v1beta1.ClearAdminProposal") +} + +func init() { + proto.RegisterFile("x/wasm/internal/types/proposal.proto", fileDescriptor_00b43267813130fb) +} + +var fileDescriptor_00b43267813130fb = []byte{ + // 679 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x55, 0xcd, 0x4e, 0xdb, 0x4a, + 0x18, 0x8d, 0x13, 0x92, 0xc0, 0x24, 0xba, 0xe2, 0xfa, 0xc2, 0xbd, 0xbe, 0xb4, 0xb2, 0x53, 0xd3, + 0x45, 0x36, 0xd8, 0x40, 0xa5, 0x56, 0xaa, 0xd4, 0x45, 0x92, 0xfe, 0xb1, 0x88, 0x84, 0x8c, 0x5a, + 0xd4, 0x6e, 0xa2, 0xb1, 0x67, 0x70, 0x87, 0xda, 0x33, 0xd1, 0xcc, 0xa4, 0x21, 0xbb, 0x3e, 0x42, + 0xf7, 0x7d, 0x81, 0xaa, 0x4f, 0x92, 0x55, 0xc5, 0x12, 0x75, 0x91, 0x96, 0xf0, 0x06, 0x5d, 0xb2, + 0xaa, 0x66, 0x6c, 0x50, 0x2a, 0xb1, 0x40, 0xc0, 0x82, 0x4d, 0x26, 0x5f, 0xbe, 0xf3, 0x9d, 0x9c, + 0x39, 0x67, 0xec, 0x01, 0xf7, 0x0f, 0xfc, 0x21, 0x14, 0xa9, 0x4f, 0xa8, 0xc4, 0x9c, 0xc2, 0xc4, + 0x97, 0xa3, 0x3e, 0x16, 0x7e, 0x9f, 0xb3, 0x3e, 0x13, 0x30, 0xf1, 0xfa, 0x9c, 0x49, 0x66, 0x2e, + 0x2b, 0x0c, 0xf2, 0x0e, 0xbc, 0x6c, 0xfd, 0xb0, 0x11, 0x62, 0x09, 0x37, 0x56, 0x96, 0x62, 0x16, + 0x33, 0x8d, 0xf0, 0xd5, 0xb7, 0x0c, 0xbc, 0x62, 0x47, 0x4c, 0xa4, 0x4c, 0xf8, 0x21, 0x14, 0xd8, + 0xcf, 0xa1, 0x7e, 0xc4, 0x08, 0xcd, 0xfb, 0xf7, 0x2e, 0xfe, 0x4b, 0xfd, 0x99, 0x41, 0xdc, 0xef, + 0x45, 0xf0, 0xf7, 0x8e, 0x64, 0x1c, 0x77, 0x18, 0xc2, 0xdb, 0xb9, 0x16, 0x73, 0x09, 0x94, 0x25, + 0x91, 0x09, 0xb6, 0x8c, 0x86, 0xd1, 0x5c, 0x08, 0xb2, 0xc2, 0x6c, 0x80, 0x1a, 0xc2, 0x22, 0xe2, + 0xa4, 0x2f, 0x09, 0xa3, 0x56, 0x51, 0xf7, 0x66, 0x7f, 0x32, 0x5f, 0x82, 0x0a, 0x1f, 0xd0, 0x1e, + 0x14, 0x56, 0xa9, 0x61, 0x34, 0xeb, 0xed, 0x8d, 0xd3, 0x89, 0xb3, 0x16, 0x13, 0xf9, 0x6e, 0x10, + 0x7a, 0x11, 0x4b, 0xfd, 0x5c, 0x6f, 0xb6, 0xac, 0x09, 0xf4, 0x3e, 0xd7, 0xd2, 0x8a, 0xa2, 0x16, + 0x42, 0x1c, 0x0b, 0x11, 0x94, 0xf9, 0x80, 0xb6, 0x84, 0xf9, 0x10, 0xfc, 0xa5, 0xa4, 0xf7, 0xc2, + 0x91, 0xc4, 0xbd, 0x88, 0x21, 0x6c, 0xcd, 0x69, 0xc6, 0xc5, 0xe9, 0xc4, 0xa9, 0xef, 0xb6, 0x76, + 0xba, 0xed, 0x91, 0xd4, 0x9a, 0x83, 0xba, 0xc2, 0x9d, 0x55, 0xe6, 0xbf, 0xa0, 0x22, 0xd8, 0x80, + 0x47, 0xd8, 0x2a, 0x6b, 0x79, 0x79, 0x65, 0x5a, 0xa0, 0x1a, 0x0e, 0x48, 0x82, 0x30, 0xb7, 0x2a, + 0xba, 0x71, 0x56, 0x9a, 0x6f, 0xc0, 0xf2, 0x16, 0x15, 0x12, 0x52, 0x49, 0xa0, 0xc4, 0xdb, 0x98, + 0xa7, 0x44, 0x08, 0xb5, 0xbf, 0x6a, 0xc3, 0x68, 0xd6, 0x36, 0x57, 0xbd, 0x0b, 0x13, 0x51, 0x92, + 0xb1, 0x10, 0x1d, 0x46, 0xf7, 0x48, 0x1c, 0x5c, 0xcc, 0xe0, 0x8e, 0x4b, 0xe0, 0xce, 0x4c, 0xa7, + 0xc3, 0xa8, 0xe4, 0x30, 0x92, 0xb7, 0xc8, 0xe6, 0x17, 0xa0, 0x0c, 0x51, 0x4a, 0x68, 0xee, 0xee, + 0x55, 0x88, 0xf4, 0xbc, 0xb9, 0x0a, 0xaa, 0x2a, 0xa5, 0x1e, 0x41, 0xda, 0xf8, 0xb9, 0x36, 0x98, + 0x4e, 0x9c, 0x8a, 0x8a, 0x64, 0xeb, 0x69, 0x50, 0x51, 0xad, 0x2d, 0xa4, 0xf6, 0x9b, 0xc0, 0x10, + 0x27, 0x79, 0x04, 0x59, 0x61, 0x3e, 0x02, 0xf3, 0x84, 0x12, 0xd9, 0x4b, 0x45, 0xac, 0x3d, 0xaf, + 0xb7, 0xef, 0x9e, 0x4e, 0x1c, 0x0b, 0xd3, 0x88, 0x21, 0x42, 0x63, 0x7f, 0x5f, 0x30, 0xea, 0x05, + 0x70, 0xd8, 0xc5, 0x42, 0xc0, 0x18, 0x07, 0x55, 0x85, 0xee, 0x8a, 0xd8, 0xdc, 0x07, 0x40, 0x0f, + 0xee, 0x0d, 0x28, 0x12, 0xd6, 0x7c, 0xa3, 0xd4, 0xac, 0x6d, 0xfe, 0xef, 0x65, 0x62, 0x3d, 0xf5, + 0x4c, 0x9c, 0x87, 0xd5, 0x61, 0x84, 0xb6, 0xd7, 0xc7, 0x13, 0xa7, 0xf0, 0xf5, 0x87, 0xd3, 0xbc, + 0xc4, 0x06, 0xd5, 0x80, 0x08, 0x16, 0x14, 0xfd, 0x73, 0xc5, 0xee, 0x7e, 0x2b, 0x82, 0xff, 0xba, + 0x24, 0xe6, 0xb7, 0x33, 0xc6, 0x2e, 0x98, 0x8f, 0x72, 0x55, 0x57, 0x4f, 0xf2, 0x9c, 0xe2, 0x72, + 0x61, 0x3e, 0x01, 0xb5, 0x34, 0x33, 0x44, 0x27, 0x57, 0xb9, 0x44, 0x72, 0x20, 0x1f, 0xe8, 0x8a, + 0xd8, 0xfd, 0x58, 0x04, 0xff, 0xbc, 0xea, 0x23, 0x28, 0x71, 0x4b, 0x1d, 0xa0, 0x6b, 0x9b, 0x19, + 0x82, 0x05, 0x8a, 0x87, 0xbd, 0xec, 0x34, 0x67, 0x7e, 0x3e, 0xfb, 0x35, 0x71, 0x16, 0x47, 0x30, + 0x4d, 0x1e, 0xbb, 0xe7, 0x2d, 0xf7, 0x0a, 0xbe, 0x50, 0x3c, 0xd4, 0x1a, 0x6f, 0xd8, 0x66, 0xf7, + 0xb3, 0x01, 0xcc, 0x4e, 0x82, 0x21, 0xbf, 0x19, 0x07, 0x66, 0xd5, 0x95, 0xae, 0xad, 0xae, 0xfd, + 0x7a, 0x7c, 0x6c, 0x17, 0x8e, 0x8e, 0xed, 0xc2, 0x97, 0xa9, 0x6d, 0x8c, 0xa7, 0xb6, 0x71, 0x38, + 0xb5, 0x8d, 0x9f, 0x53, 0xdb, 0xf8, 0x74, 0x62, 0x17, 0x0e, 0x4f, 0xec, 0xc2, 0xd1, 0x89, 0x5d, + 0x78, 0xbb, 0x3e, 0x43, 0xdf, 0x61, 0x22, 0xdd, 0x55, 0xf7, 0x8d, 0x7e, 0x53, 0xfa, 0x07, 0xf9, + 0xfa, 0xe7, 0xed, 0x13, 0x56, 0xf4, 0xc5, 0xf3, 0xe0, 0x77, 0x00, 0x00, 0x00, 0xff, 0xff, 0xd4, + 0xce, 0x48, 0x5a, 0x10, 0x07, 0x00, 0x00, +} + +func (this *StoreCodeProposal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*StoreCodeProposal) + if !ok { + that2, ok := that.(StoreCodeProposal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Title != that1.Title { + return false + } + if this.Description != that1.Description { + return false + } + if !bytes.Equal(this.RunAs, that1.RunAs) { + return false + } + if !bytes.Equal(this.WASMByteCode, that1.WASMByteCode) { + return false + } + if this.Source != that1.Source { + return false + } + if this.Builder != that1.Builder { + return false + } + if !this.InstantiatePermission.Equal(that1.InstantiatePermission) { + return false + } + return true +} +func (this *InstantiateContractProposal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*InstantiateContractProposal) + if !ok { + that2, ok := that.(InstantiateContractProposal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Title != that1.Title { + return false + } + if this.Description != that1.Description { + return false + } + if !bytes.Equal(this.RunAs, that1.RunAs) { + return false + } + if !bytes.Equal(this.Admin, that1.Admin) { + return false + } + if this.CodeID != that1.CodeID { + return false + } + if this.Label != that1.Label { + return false + } + if !bytes.Equal(this.InitMsg, that1.InitMsg) { + return false + } + if len(this.InitFunds) != len(that1.InitFunds) { + return false + } + for i := range this.InitFunds { + if !this.InitFunds[i].Equal(&that1.InitFunds[i]) { + return false + } + } + return true +} +func (this *MigrateContractProposal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*MigrateContractProposal) + if !ok { + that2, ok := that.(MigrateContractProposal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Title != that1.Title { + return false + } + if this.Description != that1.Description { + return false + } + if !bytes.Equal(this.RunAs, that1.RunAs) { + return false + } + if !bytes.Equal(this.Contract, that1.Contract) { + return false + } + if this.CodeID != that1.CodeID { + return false + } + if !bytes.Equal(this.MigrateMsg, that1.MigrateMsg) { + return false + } + return true +} +func (this *UpdateAdminProposal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*UpdateAdminProposal) + if !ok { + that2, ok := that.(UpdateAdminProposal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Title != that1.Title { + return false + } + if this.Description != that1.Description { + return false + } + if !bytes.Equal(this.NewAdmin, that1.NewAdmin) { + return false + } + if !bytes.Equal(this.Contract, that1.Contract) { + return false + } + return true +} +func (this *ClearAdminProposal) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ClearAdminProposal) + if !ok { + that2, ok := that.(ClearAdminProposal) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Title != that1.Title { + return false + } + if this.Description != that1.Description { + return false + } + if !bytes.Equal(this.Contract, that1.Contract) { + return false + } + return true +} +func (m *StoreCodeProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *StoreCodeProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *StoreCodeProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.InstantiatePermission != nil { + { + size, err := m.InstantiatePermission.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintProposal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x3a + } + if len(m.Builder) > 0 { + i -= len(m.Builder) + copy(dAtA[i:], m.Builder) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Builder))) + i-- + dAtA[i] = 0x32 + } + if len(m.Source) > 0 { + i -= len(m.Source) + copy(dAtA[i:], m.Source) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Source))) + i-- + dAtA[i] = 0x2a + } + if len(m.WASMByteCode) > 0 { + i -= len(m.WASMByteCode) + copy(dAtA[i:], m.WASMByteCode) + i = encodeVarintProposal(dAtA, i, uint64(len(m.WASMByteCode))) + i-- + dAtA[i] = 0x22 + } + if len(m.RunAs) > 0 { + i -= len(m.RunAs) + copy(dAtA[i:], m.RunAs) + i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *InstantiateContractProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *InstantiateContractProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *InstantiateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.InitFunds) > 0 { + for iNdEx := len(m.InitFunds) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.InitFunds[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintProposal(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x42 + } + } + if len(m.InitMsg) > 0 { + i -= len(m.InitMsg) + copy(dAtA[i:], m.InitMsg) + i = encodeVarintProposal(dAtA, i, uint64(len(m.InitMsg))) + i-- + dAtA[i] = 0x3a + } + if len(m.Label) > 0 { + i -= len(m.Label) + copy(dAtA[i:], m.Label) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Label))) + i-- + dAtA[i] = 0x32 + } + if m.CodeID != 0 { + i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x28 + } + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0x22 + } + if len(m.RunAs) > 0 { + i -= len(m.RunAs) + copy(dAtA[i:], m.RunAs) + i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MigrateContractProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MigrateContractProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MigrateContractProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.MigrateMsg) > 0 { + i -= len(m.MigrateMsg) + copy(dAtA[i:], m.MigrateMsg) + i = encodeVarintProposal(dAtA, i, uint64(len(m.MigrateMsg))) + i-- + dAtA[i] = 0x32 + } + if m.CodeID != 0 { + i = encodeVarintProposal(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x28 + } + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x22 + } + if len(m.RunAs) > 0 { + i -= len(m.RunAs) + copy(dAtA[i:], m.RunAs) + i = encodeVarintProposal(dAtA, i, uint64(len(m.RunAs))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *UpdateAdminProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *UpdateAdminProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *UpdateAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x22 + } + if len(m.NewAdmin) > 0 { + i -= len(m.NewAdmin) + copy(dAtA[i:], m.NewAdmin) + i = encodeVarintProposal(dAtA, i, uint64(len(m.NewAdmin))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ClearAdminProposal) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ClearAdminProposal) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ClearAdminProposal) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Contract) > 0 { + i -= len(m.Contract) + copy(dAtA[i:], m.Contract) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Contract))) + i-- + dAtA[i] = 0x1a + } + if len(m.Description) > 0 { + i -= len(m.Description) + copy(dAtA[i:], m.Description) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Description))) + i-- + dAtA[i] = 0x12 + } + if len(m.Title) > 0 { + i -= len(m.Title) + copy(dAtA[i:], m.Title) + i = encodeVarintProposal(dAtA, i, uint64(len(m.Title))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintProposal(dAtA []byte, offset int, v uint64) int { + offset -= sovProposal(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *StoreCodeProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.RunAs) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.WASMByteCode) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Source) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Builder) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + if m.InstantiatePermission != nil { + l = m.InstantiatePermission.Size() + n += 1 + l + sovProposal(uint64(l)) + } + return n +} + +func (m *InstantiateContractProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.RunAs) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + if m.CodeID != 0 { + n += 1 + sovProposal(uint64(m.CodeID)) + } + l = len(m.Label) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.InitMsg) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + if len(m.InitFunds) > 0 { + for _, e := range m.InitFunds { + l = e.Size() + n += 1 + l + sovProposal(uint64(l)) + } + } + return n +} + +func (m *MigrateContractProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.RunAs) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + if m.CodeID != 0 { + n += 1 + sovProposal(uint64(m.CodeID)) + } + l = len(m.MigrateMsg) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + return n +} + +func (m *UpdateAdminProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.NewAdmin) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + return n +} + +func (m *ClearAdminProposal) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Title) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Description) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + l = len(m.Contract) + if l > 0 { + n += 1 + l + sovProposal(uint64(l)) + } + return n +} + +func sovProposal(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozProposal(x uint64) (n int) { + return sovProposal(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *StoreCodeProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: StoreCodeProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: StoreCodeProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RunAs = append(m.RunAs[:0], dAtA[iNdEx:postIndex]...) + if m.RunAs == nil { + m.RunAs = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field WASMByteCode", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.WASMByteCode = append(m.WASMByteCode[:0], dAtA[iNdEx:postIndex]...) + if m.WASMByteCode == nil { + m.WASMByteCode = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Source = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Builder = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InstantiatePermission", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.InstantiatePermission == nil { + m.InstantiatePermission = &AccessConfig{} + } + if err := m.InstantiatePermission.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposal(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *InstantiateContractProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: InstantiateContractProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: InstantiateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RunAs = append(m.RunAs[:0], dAtA[iNdEx:postIndex]...) + if m.RunAs == nil { + m.RunAs = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = append(m.Admin[:0], dAtA[iNdEx:postIndex]...) + if m.Admin == nil { + m.Admin = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Label = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 7: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitMsg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitMsg = append(m.InitMsg[:0], dAtA[iNdEx:postIndex]...) + if m.InitMsg == nil { + m.InitMsg = []byte{} + } + iNdEx = postIndex + case 8: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InitFunds", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.InitFunds = append(m.InitFunds, types.Coin{}) + if err := m.InitFunds[len(m.InitFunds)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposal(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MigrateContractProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MigrateContractProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MigrateContractProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field RunAs", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.RunAs = append(m.RunAs[:0], dAtA[iNdEx:postIndex]...) + if m.RunAs == nil { + m.RunAs = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + case 5: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field MigrateMsg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.MigrateMsg = append(m.MigrateMsg[:0], dAtA[iNdEx:postIndex]...) + if m.MigrateMsg == nil { + m.MigrateMsg = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposal(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *UpdateAdminProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: UpdateAdminProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: UpdateAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field NewAdmin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.NewAdmin = append(m.NewAdmin[:0], dAtA[iNdEx:postIndex]...) + if m.NewAdmin == nil { + m.NewAdmin = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposal(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ClearAdminProposal) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ClearAdminProposal: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ClearAdminProposal: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Title", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Title = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Description", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Description = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Contract", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowProposal + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthProposal + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthProposal + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Contract = append(m.Contract[:0], dAtA[iNdEx:postIndex]...) + if m.Contract == nil { + m.Contract = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipProposal(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthProposal + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipProposal(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowProposal + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthProposal + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupProposal + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthProposal + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthProposal = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowProposal = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupProposal = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/wasm/internal/types/proposal.proto b/x/wasm/internal/types/proposal.proto new file mode 100644 index 0000000000..a1a6d30d20 --- /dev/null +++ b/x/wasm/internal/types/proposal.proto @@ -0,0 +1,68 @@ +syntax = "proto3"; +package wasmd.x.wasmd.v1beta1; + +import "gogoproto/gogo.proto"; +import "cosmos/base/v1beta1/coin.proto"; +import "x/wasm/internal/types/types.proto"; + +option go_package = "github.com/CosmWasm/wasmd/x/wasmd/internal/types"; +option (gogoproto.goproto_stringer_all) = false; +option (gogoproto.goproto_getters_all) = false; +option (gogoproto.equal_all) = true; + +message StoreCodeProposal { + string title = 1; + string description = 2; + // RunAs is the address that is passed to the contract's environment as sender + bytes run_as = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + // WASMByteCode can be raw or gzip compressed + bytes wasm_byte_code = 4 [(gogoproto.customname) = "WASMByteCode"]; + // Source is a valid absolute HTTPS URI to the contract's source code, optional + string source = 5; + // Builder is a valid docker image name with tag, optional + string builder = 6; + // InstantiatePermission to apply on contract creation, optional + AccessConfig InstantiatePermission = 7; +} + +// InstantiateContractProposal gov proposal content type to instantiate a contract. +message InstantiateContractProposal { + string title = 1; + string description = 2; + + + // RunAs is the address that is passed to the contract's environment as sender + bytes run_as = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + // Admin is an optional address that can execute migrations + bytes admin = 4 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + uint64 code_id = 5 [(gogoproto.customname) = "CodeID"]; + string label = 6; + bytes init_msg = 7 [(gogoproto.casttype) = "encoding/json.RawMessage"]; + repeated cosmos.base.v1beta1.Coin init_funds = 8 [(gogoproto.nullable) = false, (gogoproto.castrepeated) = "github.com/cosmos/cosmos-sdk/types.Coins"]; +} + +// MigrateContractProposal gov proposal content type to migrate a contract. +message MigrateContractProposal { + string title = 1; + string description = 2; + // RunAs is the address that is passed to the contract's environment as sender + bytes run_as = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes contract = 4 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + uint64 code_id = 5 [(gogoproto.customname) = "CodeID"]; + bytes migrate_msg = 6 [(gogoproto.casttype) = "encoding/json.RawMessage"]; +} + +// UpdateAdminProposal gov proposal content type to set an admin for a contract. +message UpdateAdminProposal { + string title = 1; + string description = 2; + bytes new_admin = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress", (gogoproto.moretags) = "yaml:\"new_admin\""]; + bytes contract = 4 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} + +// ClearAdminProposal gov proposal content type to clear the admin of a contract. +message ClearAdminProposal { + string title = 1; + string description = 2; + bytes contract = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} diff --git a/x/wasm/internal/types/proposal_test.go b/x/wasm/internal/types/proposal_test.go index 5f2a57bbab..7538018e57 100644 --- a/x/wasm/internal/types/proposal_test.go +++ b/x/wasm/internal/types/proposal_test.go @@ -6,71 +6,74 @@ import ( "testing" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/gov" govtypes "github.com/cosmos/cosmos-sdk/x/gov/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "gopkg.in/yaml.v2" ) -func TestValidateWasmProposal(t *testing.T) { +func TestValidateProposalCommons(t *testing.T) { + type commonProposal struct { + Title, Description string + } + specs := map[string]struct { - src WasmProposal + src commonProposal expErr bool }{ - "all good": {src: WasmProposal{ + "all good": {src: commonProposal{ Title: "Foo", Description: "Bar", }}, "prevent empty title": { - src: WasmProposal{ + src: commonProposal{ Description: "Bar", }, expErr: true, }, "prevent white space only title": { - src: WasmProposal{ + src: commonProposal{ Title: " ", Description: "Bar", }, expErr: true, }, "prevent leading white spaces in title": { - src: WasmProposal{ + src: commonProposal{ Title: " Foo", Description: "Bar", }, expErr: true, }, "prevent title exceeds max length ": { - src: WasmProposal{ + src: commonProposal{ Title: strings.Repeat("a", govtypes.MaxTitleLength+1), Description: "Bar", }, expErr: true, }, "prevent empty description": { - src: WasmProposal{ + src: commonProposal{ Title: "Foo", }, expErr: true, }, "prevent leading white spaces in description": { - src: WasmProposal{ + src: commonProposal{ Title: "Foo", Description: " Bar", }, expErr: true, }, "prevent white space only description": { - src: WasmProposal{ + src: commonProposal{ Title: "Foo", Description: " ", }, expErr: true, }, "prevent descr exceeds max length ": { - src: WasmProposal{ + src: commonProposal{ Title: "Foo", Description: strings.Repeat("a", govtypes.MaxDescriptionLength+1), }, @@ -79,7 +82,7 @@ func TestValidateWasmProposal(t *testing.T) { } for msg, spec := range specs { t.Run(msg, func(t *testing.T) { - err := spec.src.ValidateBasic() + err := validateProposalCommons(spec.src.Title, spec.src.Description) if spec.expErr { require.Error(t, err) } else { @@ -96,7 +99,7 @@ func TestValidateStoreCodeProposal(t *testing.T) { ) specs := map[string]struct { - src StoreCodeProposal + src *StoreCodeProposal expErr bool }{ "all good": { @@ -104,7 +107,7 @@ func TestValidateStoreCodeProposal(t *testing.T) { }, "with instantiate permission": { src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - accessConfig := OnlyAddress.With(anyAddress) + accessConfig := AccessTypeOnlyAddress.With(anyAddress) p.InstantiatePermission = &accessConfig }), }, @@ -116,7 +119,7 @@ func TestValidateStoreCodeProposal(t *testing.T) { }, "base data missing": { src: StoreCodeProposalFixture(func(p *StoreCodeProposal) { - p.WasmProposal = WasmProposal{} + p.Title = "" }), expErr: true, }, @@ -181,7 +184,7 @@ func TestValidateInstantiateContractProposal(t *testing.T) { ) specs := map[string]struct { - src InstantiateContractProposal + src *InstantiateContractProposal expErr bool }{ "all good": { @@ -204,7 +207,7 @@ func TestValidateInstantiateContractProposal(t *testing.T) { }, "base data missing": { src: InstantiateContractProposalFixture(func(p *InstantiateContractProposal) { - p.WasmProposal = WasmProposal{} + p.Title = "" }), expErr: true, }, @@ -269,7 +272,7 @@ func TestValidateMigrateContractProposal(t *testing.T) { ) specs := map[string]struct { - src MigrateContractProposal + src *MigrateContractProposal expErr bool }{ "all good": { @@ -282,7 +285,7 @@ func TestValidateMigrateContractProposal(t *testing.T) { }, "base data missing": { src: MigrateContractProposalFixture(func(p *MigrateContractProposal) { - p.WasmProposal = WasmProposal{} + p.Title = "" }), expErr: true, }, @@ -335,7 +338,7 @@ func TestValidateUpdateAdminProposal(t *testing.T) { ) specs := map[string]struct { - src UpdateAdminProposal + src *UpdateAdminProposal expErr bool }{ "all good": { @@ -343,7 +346,7 @@ func TestValidateUpdateAdminProposal(t *testing.T) { }, "base data missing": { src: UpdateAdminProposalFixture(func(p *UpdateAdminProposal) { - p.WasmProposal = WasmProposal{} + p.Title = "" }), expErr: true, }, @@ -390,7 +393,7 @@ func TestValidateClearAdminProposal(t *testing.T) { ) specs := map[string]struct { - src ClearAdminProposal + src *ClearAdminProposal expErr bool }{ "all good": { @@ -398,7 +401,7 @@ func TestValidateClearAdminProposal(t *testing.T) { }, "base data missing": { src: ClearAdminProposalFixture(func(p *ClearAdminProposal) { - p.WasmProposal = WasmProposal{} + p.Title = "" }), expErr: true, }, @@ -429,7 +432,7 @@ func TestValidateClearAdminProposal(t *testing.T) { func TestProposalStrings(t *testing.T) { specs := map[string]struct { - src gov.Content + src govtypes.Content exp string }{ "store code": { @@ -524,7 +527,7 @@ func TestProposalStrings(t *testing.T) { func TestProposalYaml(t *testing.T) { specs := map[string]struct { - src gov.Content + src govtypes.Content exp string }{ "store code": { diff --git a/x/wasm/internal/types/query.pb.go b/x/wasm/internal/types/query.pb.go new file mode 100644 index 0000000000..b09d45aacf --- /dev/null +++ b/x/wasm/internal/types/query.pb.go @@ -0,0 +1,4279 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: x/wasm/internal/types/query.proto + +package types + +import ( + bytes "bytes" + context "context" + encoding_json "encoding/json" + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + grpc1 "github.com/gogo/protobuf/grpc" + proto "github.com/gogo/protobuf/proto" + empty "github.com/golang/protobuf/ptypes/empty" + github_com_tendermint_tendermint_libs_bytes "github.com/tendermint/tendermint/libs/bytes" + _ "google.golang.org/genproto/googleapis/api/annotations" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC method +type QueryContractInfoRequest struct { + // address is the address of the contract to query + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` +} + +func (m *QueryContractInfoRequest) Reset() { *m = QueryContractInfoRequest{} } +func (m *QueryContractInfoRequest) String() string { return proto.CompactTextString(m) } +func (*QueryContractInfoRequest) ProtoMessage() {} +func (*QueryContractInfoRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{0} +} +func (m *QueryContractInfoRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractInfoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractInfoRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractInfoRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractInfoRequest.Merge(m, src) +} +func (m *QueryContractInfoRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryContractInfoRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractInfoRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractInfoRequest proto.InternalMessageInfo + +// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC method +type QueryContractInfoResponse struct { + // address is the address of the contract + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` + *ContractInfo `protobuf:"bytes,2,opt,name=ContractInfo,proto3,embedded=ContractInfo" json:""` +} + +func (m *QueryContractInfoResponse) Reset() { *m = QueryContractInfoResponse{} } +func (m *QueryContractInfoResponse) String() string { return proto.CompactTextString(m) } +func (*QueryContractInfoResponse) ProtoMessage() {} +func (*QueryContractInfoResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{1} +} +func (m *QueryContractInfoResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractInfoResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractInfoResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractInfoResponse.Merge(m, src) +} +func (m *QueryContractInfoResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryContractInfoResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractInfoResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractInfoResponse proto.InternalMessageInfo + +type QueryContractHistoryRequest struct { + // address is the address of the contract to query + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` +} + +func (m *QueryContractHistoryRequest) Reset() { *m = QueryContractHistoryRequest{} } +func (m *QueryContractHistoryRequest) String() string { return proto.CompactTextString(m) } +func (*QueryContractHistoryRequest) ProtoMessage() {} +func (*QueryContractHistoryRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{2} +} +func (m *QueryContractHistoryRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractHistoryRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractHistoryRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractHistoryRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractHistoryRequest.Merge(m, src) +} +func (m *QueryContractHistoryRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryContractHistoryRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractHistoryRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractHistoryRequest proto.InternalMessageInfo + +type QueryContractHistoryResponse struct { + Entries []ContractCodeHistoryEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries"` +} + +func (m *QueryContractHistoryResponse) Reset() { *m = QueryContractHistoryResponse{} } +func (m *QueryContractHistoryResponse) String() string { return proto.CompactTextString(m) } +func (*QueryContractHistoryResponse) ProtoMessage() {} +func (*QueryContractHistoryResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{3} +} +func (m *QueryContractHistoryResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractHistoryResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractHistoryResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractHistoryResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractHistoryResponse.Merge(m, src) +} +func (m *QueryContractHistoryResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryContractHistoryResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractHistoryResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractHistoryResponse proto.InternalMessageInfo + +type QueryContractsByCodeRequest struct { + CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` +} + +func (m *QueryContractsByCodeRequest) Reset() { *m = QueryContractsByCodeRequest{} } +func (m *QueryContractsByCodeRequest) String() string { return proto.CompactTextString(m) } +func (*QueryContractsByCodeRequest) ProtoMessage() {} +func (*QueryContractsByCodeRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{4} +} +func (m *QueryContractsByCodeRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractsByCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractsByCodeRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractsByCodeRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractsByCodeRequest.Merge(m, src) +} +func (m *QueryContractsByCodeRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryContractsByCodeRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractsByCodeRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractsByCodeRequest proto.InternalMessageInfo + +// ContractInfoWithAddress adds the address (key) to the ContractInfo representation +type ContractInfoWithAddress struct { + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` + *ContractInfo `protobuf:"bytes,2,opt,name=ContractInfo,proto3,embedded=ContractInfo" json:""` +} + +func (m *ContractInfoWithAddress) Reset() { *m = ContractInfoWithAddress{} } +func (m *ContractInfoWithAddress) String() string { return proto.CompactTextString(m) } +func (*ContractInfoWithAddress) ProtoMessage() {} +func (*ContractInfoWithAddress) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{5} +} +func (m *ContractInfoWithAddress) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ContractInfoWithAddress) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ContractInfoWithAddress.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ContractInfoWithAddress) XXX_Merge(src proto.Message) { + xxx_messageInfo_ContractInfoWithAddress.Merge(m, src) +} +func (m *ContractInfoWithAddress) XXX_Size() int { + return m.Size() +} +func (m *ContractInfoWithAddress) XXX_DiscardUnknown() { + xxx_messageInfo_ContractInfoWithAddress.DiscardUnknown(m) +} + +var xxx_messageInfo_ContractInfoWithAddress proto.InternalMessageInfo + +type QueryContractsByCodeResponse struct { + ContractInfos []ContractInfoWithAddress `protobuf:"bytes,1,rep,name=contract_infos,json=contractInfos,proto3" json:"contract_infos"` +} + +func (m *QueryContractsByCodeResponse) Reset() { *m = QueryContractsByCodeResponse{} } +func (m *QueryContractsByCodeResponse) String() string { return proto.CompactTextString(m) } +func (*QueryContractsByCodeResponse) ProtoMessage() {} +func (*QueryContractsByCodeResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{6} +} +func (m *QueryContractsByCodeResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryContractsByCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryContractsByCodeResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryContractsByCodeResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryContractsByCodeResponse.Merge(m, src) +} +func (m *QueryContractsByCodeResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryContractsByCodeResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryContractsByCodeResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryContractsByCodeResponse proto.InternalMessageInfo + +type QueryAllContractStateRequest struct { + // address is the address of the contract + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` +} + +func (m *QueryAllContractStateRequest) Reset() { *m = QueryAllContractStateRequest{} } +func (m *QueryAllContractStateRequest) String() string { return proto.CompactTextString(m) } +func (*QueryAllContractStateRequest) ProtoMessage() {} +func (*QueryAllContractStateRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{7} +} +func (m *QueryAllContractStateRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAllContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAllContractStateRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAllContractStateRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllContractStateRequest.Merge(m, src) +} +func (m *QueryAllContractStateRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryAllContractStateRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllContractStateRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAllContractStateRequest proto.InternalMessageInfo + +type QueryAllContractStateResponse struct { + Models []Model `protobuf:"bytes,1,rep,name=models,proto3" json:"models"` +} + +func (m *QueryAllContractStateResponse) Reset() { *m = QueryAllContractStateResponse{} } +func (m *QueryAllContractStateResponse) String() string { return proto.CompactTextString(m) } +func (*QueryAllContractStateResponse) ProtoMessage() {} +func (*QueryAllContractStateResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{8} +} +func (m *QueryAllContractStateResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryAllContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryAllContractStateResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryAllContractStateResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryAllContractStateResponse.Merge(m, src) +} +func (m *QueryAllContractStateResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryAllContractStateResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryAllContractStateResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryAllContractStateResponse proto.InternalMessageInfo + +type QueryRawContractStateRequest struct { + // address is the address of the contract + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` + QueryData []byte `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3" json:"query_data,omitempty"` +} + +func (m *QueryRawContractStateRequest) Reset() { *m = QueryRawContractStateRequest{} } +func (m *QueryRawContractStateRequest) String() string { return proto.CompactTextString(m) } +func (*QueryRawContractStateRequest) ProtoMessage() {} +func (*QueryRawContractStateRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{9} +} +func (m *QueryRawContractStateRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryRawContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRawContractStateRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryRawContractStateRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRawContractStateRequest.Merge(m, src) +} +func (m *QueryRawContractStateRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryRawContractStateRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRawContractStateRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRawContractStateRequest proto.InternalMessageInfo + +type QueryRawContractStateResponse struct { + Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"` +} + +func (m *QueryRawContractStateResponse) Reset() { *m = QueryRawContractStateResponse{} } +func (m *QueryRawContractStateResponse) String() string { return proto.CompactTextString(m) } +func (*QueryRawContractStateResponse) ProtoMessage() {} +func (*QueryRawContractStateResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{10} +} +func (m *QueryRawContractStateResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryRawContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryRawContractStateResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryRawContractStateResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryRawContractStateResponse.Merge(m, src) +} +func (m *QueryRawContractStateResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryRawContractStateResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryRawContractStateResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryRawContractStateResponse proto.InternalMessageInfo + +type QuerySmartContractStateRequest struct { + // address is the address of the contract + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,1,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty"` + QueryData []byte `protobuf:"bytes,2,opt,name=query_data,json=queryData,proto3" json:"query_data,omitempty"` +} + +func (m *QuerySmartContractStateRequest) Reset() { *m = QuerySmartContractStateRequest{} } +func (m *QuerySmartContractStateRequest) String() string { return proto.CompactTextString(m) } +func (*QuerySmartContractStateRequest) ProtoMessage() {} +func (*QuerySmartContractStateRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{11} +} +func (m *QuerySmartContractStateRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySmartContractStateRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySmartContractStateRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QuerySmartContractStateRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySmartContractStateRequest.Merge(m, src) +} +func (m *QuerySmartContractStateRequest) XXX_Size() int { + return m.Size() +} +func (m *QuerySmartContractStateRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySmartContractStateRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySmartContractStateRequest proto.InternalMessageInfo + +type QuerySmartContractStateResponse struct { + Data encoding_json.RawMessage `protobuf:"bytes,1,opt,name=data,proto3,casttype=encoding/json.RawMessage" json:"data,omitempty"` +} + +func (m *QuerySmartContractStateResponse) Reset() { *m = QuerySmartContractStateResponse{} } +func (m *QuerySmartContractStateResponse) String() string { return proto.CompactTextString(m) } +func (*QuerySmartContractStateResponse) ProtoMessage() {} +func (*QuerySmartContractStateResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{12} +} +func (m *QuerySmartContractStateResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QuerySmartContractStateResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QuerySmartContractStateResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QuerySmartContractStateResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QuerySmartContractStateResponse.Merge(m, src) +} +func (m *QuerySmartContractStateResponse) XXX_Size() int { + return m.Size() +} +func (m *QuerySmartContractStateResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QuerySmartContractStateResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QuerySmartContractStateResponse proto.InternalMessageInfo + +type QueryCodeRequest struct { + CodeId uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` +} + +func (m *QueryCodeRequest) Reset() { *m = QueryCodeRequest{} } +func (m *QueryCodeRequest) String() string { return proto.CompactTextString(m) } +func (*QueryCodeRequest) ProtoMessage() {} +func (*QueryCodeRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{13} +} +func (m *QueryCodeRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCodeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCodeRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryCodeRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCodeRequest.Merge(m, src) +} +func (m *QueryCodeRequest) XXX_Size() int { + return m.Size() +} +func (m *QueryCodeRequest) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCodeRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCodeRequest proto.InternalMessageInfo + +type CodeInfoResponse struct { + CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"id"` + Creator github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=creator,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"creator,omitempty"` + DataHash github_com_tendermint_tendermint_libs_bytes.HexBytes `protobuf:"bytes,3,opt,name=data_hash,json=dataHash,proto3,casttype=github.com/tendermint/tendermint/libs/bytes.HexBytes" json:"data_hash,omitempty"` + Source string `protobuf:"bytes,4,opt,name=source,proto3" json:"source,omitempty"` + Builder string `protobuf:"bytes,5,opt,name=builder,proto3" json:"builder,omitempty"` +} + +func (m *CodeInfoResponse) Reset() { *m = CodeInfoResponse{} } +func (m *CodeInfoResponse) String() string { return proto.CompactTextString(m) } +func (*CodeInfoResponse) ProtoMessage() {} +func (*CodeInfoResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{14} +} +func (m *CodeInfoResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CodeInfoResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CodeInfoResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CodeInfoResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_CodeInfoResponse.Merge(m, src) +} +func (m *CodeInfoResponse) XXX_Size() int { + return m.Size() +} +func (m *CodeInfoResponse) XXX_DiscardUnknown() { + xxx_messageInfo_CodeInfoResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_CodeInfoResponse proto.InternalMessageInfo + +type QueryCodeResponse struct { + *CodeInfoResponse `protobuf:"bytes,1,opt,name=code_info,json=codeInfo,proto3,embedded=code_info" json:""` + Data []byte `protobuf:"bytes,2,opt,name=data,proto3" json:"data"` +} + +func (m *QueryCodeResponse) Reset() { *m = QueryCodeResponse{} } +func (m *QueryCodeResponse) String() string { return proto.CompactTextString(m) } +func (*QueryCodeResponse) ProtoMessage() {} +func (*QueryCodeResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{15} +} +func (m *QueryCodeResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCodeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCodeResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryCodeResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCodeResponse.Merge(m, src) +} +func (m *QueryCodeResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryCodeResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCodeResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCodeResponse proto.InternalMessageInfo + +type QueryCodesResponse struct { + CodeInfos []CodeInfoResponse `protobuf:"bytes,1,rep,name=code_infos,json=codeInfos,proto3" json:"code_infos"` +} + +func (m *QueryCodesResponse) Reset() { *m = QueryCodesResponse{} } +func (m *QueryCodesResponse) String() string { return proto.CompactTextString(m) } +func (*QueryCodesResponse) ProtoMessage() {} +func (*QueryCodesResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_845473e9a3330642, []int{16} +} +func (m *QueryCodesResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *QueryCodesResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_QueryCodesResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *QueryCodesResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_QueryCodesResponse.Merge(m, src) +} +func (m *QueryCodesResponse) XXX_Size() int { + return m.Size() +} +func (m *QueryCodesResponse) XXX_DiscardUnknown() { + xxx_messageInfo_QueryCodesResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_QueryCodesResponse proto.InternalMessageInfo + +func init() { + proto.RegisterType((*QueryContractInfoRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryContractInfoRequest") + proto.RegisterType((*QueryContractInfoResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryContractInfoResponse") + proto.RegisterType((*QueryContractHistoryRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryContractHistoryRequest") + proto.RegisterType((*QueryContractHistoryResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryContractHistoryResponse") + proto.RegisterType((*QueryContractsByCodeRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryContractsByCodeRequest") + proto.RegisterType((*ContractInfoWithAddress)(nil), "wasmd.x.wasmd.v1beta1.ContractInfoWithAddress") + proto.RegisterType((*QueryContractsByCodeResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryContractsByCodeResponse") + proto.RegisterType((*QueryAllContractStateRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryAllContractStateRequest") + proto.RegisterType((*QueryAllContractStateResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryAllContractStateResponse") + proto.RegisterType((*QueryRawContractStateRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryRawContractStateRequest") + proto.RegisterType((*QueryRawContractStateResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryRawContractStateResponse") + proto.RegisterType((*QuerySmartContractStateRequest)(nil), "wasmd.x.wasmd.v1beta1.QuerySmartContractStateRequest") + proto.RegisterType((*QuerySmartContractStateResponse)(nil), "wasmd.x.wasmd.v1beta1.QuerySmartContractStateResponse") + proto.RegisterType((*QueryCodeRequest)(nil), "wasmd.x.wasmd.v1beta1.QueryCodeRequest") + proto.RegisterType((*CodeInfoResponse)(nil), "wasmd.x.wasmd.v1beta1.CodeInfoResponse") + proto.RegisterType((*QueryCodeResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryCodeResponse") + proto.RegisterType((*QueryCodesResponse)(nil), "wasmd.x.wasmd.v1beta1.QueryCodesResponse") +} + +func init() { proto.RegisterFile("x/wasm/internal/types/query.proto", fileDescriptor_845473e9a3330642) } + +var fileDescriptor_845473e9a3330642 = []byte{ + // 1071 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xcc, 0x57, 0xcf, 0x6f, 0x1b, 0x45, + 0x14, 0xce, 0xa4, 0x8e, 0x13, 0x4f, 0x03, 0x98, 0x51, 0x69, 0x8d, 0xeb, 0xae, 0xc3, 0x82, 0xa8, + 0x0b, 0xea, 0x6e, 0x12, 0xb7, 0x15, 0x3f, 0x4e, 0x71, 0x5a, 0x29, 0x15, 0x14, 0xd4, 0x8d, 0x50, + 0x25, 0x7a, 0x88, 0xc6, 0xbb, 0x13, 0x7b, 0x5b, 0x7b, 0xc7, 0xdd, 0x19, 0x93, 0x58, 0x51, 0x84, + 0xe0, 0x88, 0x38, 0x20, 0xf5, 0x82, 0xc4, 0x3f, 0x80, 0x10, 0xdc, 0x41, 0x5c, 0x38, 0xe6, 0x18, + 0x89, 0x0b, 0x27, 0x0b, 0x1c, 0x4e, 0xf9, 0x13, 0x72, 0x42, 0x3b, 0xfb, 0xd6, 0x5d, 0x3b, 0x59, + 0xdb, 0x41, 0x44, 0xf4, 0xe2, 0x9d, 0xf1, 0xbc, 0x1f, 0xdf, 0xf7, 0xed, 0xcc, 0x7b, 0x3b, 0xf8, + 0xb5, 0x6d, 0x73, 0x8b, 0x8a, 0xa6, 0xe9, 0x7a, 0x92, 0xf9, 0x1e, 0x6d, 0x98, 0xb2, 0xd3, 0x62, + 0xc2, 0x7c, 0xd2, 0x66, 0x7e, 0xc7, 0x68, 0xf9, 0x5c, 0x72, 0xf2, 0x4a, 0x60, 0xe0, 0x18, 0xdb, + 0x46, 0xf8, 0xfc, 0x6c, 0xa9, 0xca, 0x24, 0x5d, 0xca, 0x5f, 0xa8, 0xf1, 0x1a, 0x57, 0x16, 0x66, + 0x30, 0x0a, 0x8d, 0xf3, 0x09, 0xf1, 0xd4, 0x2f, 0x98, 0x5c, 0xae, 0x71, 0x5e, 0x6b, 0x30, 0x53, + 0xcd, 0xaa, 0xed, 0x4d, 0x93, 0x35, 0x5b, 0x12, 0x92, 0xe5, 0x0b, 0xb0, 0x48, 0x5b, 0xae, 0x49, + 0x3d, 0x8f, 0x4b, 0x2a, 0x5d, 0xee, 0x81, 0xab, 0x5e, 0xc3, 0xb9, 0xfb, 0x01, 0xb2, 0x55, 0xee, + 0x49, 0x9f, 0xda, 0xf2, 0xae, 0xb7, 0xc9, 0x2d, 0xf6, 0xa4, 0xcd, 0x84, 0x24, 0x1f, 0xe0, 0x59, + 0xea, 0x38, 0x3e, 0x13, 0x22, 0x87, 0x16, 0x50, 0x69, 0xbe, 0xb2, 0x74, 0xd4, 0x2d, 0x5e, 0xaf, + 0xb9, 0xb2, 0xde, 0xae, 0x1a, 0x36, 0x6f, 0x9a, 0x36, 0x17, 0x4d, 0x2e, 0xe0, 0x71, 0x5d, 0x38, + 0x8f, 0x01, 0xd5, 0x8a, 0x6d, 0xaf, 0x84, 0x8e, 0x56, 0x14, 0x41, 0xff, 0x15, 0xe1, 0x57, 0x4f, + 0xc8, 0x24, 0x5a, 0xdc, 0x13, 0xec, 0x3f, 0x4d, 0x45, 0xee, 0xe3, 0xf9, 0x78, 0x92, 0xdc, 0xf4, + 0x02, 0x2a, 0x9d, 0x5f, 0x7e, 0xdd, 0x38, 0x51, 0x75, 0x23, 0x6e, 0x5a, 0x99, 0xdb, 0xef, 0x16, + 0xd1, 0x61, 0xb7, 0x38, 0x65, 0x0d, 0x84, 0xd0, 0x1f, 0xe1, 0xcb, 0x03, 0xe0, 0xd7, 0x5c, 0x21, + 0xb9, 0xdf, 0x39, 0x13, 0xa5, 0x38, 0x2e, 0x9c, 0x9c, 0x0b, 0xb4, 0xfa, 0x18, 0xcf, 0x32, 0x4f, + 0xfa, 0x2e, 0x0b, 0x92, 0x9d, 0x2b, 0x9d, 0x5f, 0x36, 0xc7, 0x30, 0x5b, 0xe5, 0x0e, 0x83, 0x20, + 0x77, 0x3c, 0xe9, 0x77, 0x2a, 0xa9, 0xbd, 0x80, 0x61, 0x14, 0x45, 0xbf, 0x35, 0x44, 0x4e, 0x54, + 0x3a, 0x81, 0x4b, 0x44, 0xee, 0x12, 0x9e, 0xb5, 0xb9, 0xc3, 0x36, 0x5c, 0x47, 0x91, 0x4b, 0x59, + 0xe9, 0x60, 0x7a, 0xd7, 0xd1, 0x7f, 0x41, 0xf8, 0x52, 0x5c, 0xa5, 0x07, 0xae, 0xac, 0x03, 0x9b, + 0xe7, 0xfe, 0x85, 0xee, 0x0c, 0x89, 0xdc, 0xe7, 0x0c, 0x22, 0x3f, 0xc4, 0x2f, 0xda, 0xb0, 0xb4, + 0xe1, 0x7a, 0x9b, 0x3c, 0xd2, 0xda, 0x98, 0x20, 0x69, 0x4c, 0x07, 0x90, 0xfa, 0x05, 0x3b, 0xb6, + 0x2c, 0xf4, 0xc7, 0x90, 0x7c, 0xa5, 0xd1, 0x88, 0xfc, 0xd6, 0x25, 0x95, 0xec, 0x4c, 0xb6, 0xd3, + 0x43, 0x7c, 0x25, 0x21, 0x19, 0x50, 0x7d, 0x0f, 0xa7, 0x9b, 0xdc, 0x61, 0x8d, 0x88, 0x62, 0x21, + 0x81, 0xe2, 0xbd, 0xc0, 0x08, 0x08, 0x81, 0x87, 0xfe, 0x15, 0x02, 0x2a, 0x16, 0xdd, 0x3a, 0x73, + 0x2a, 0xe4, 0x0a, 0xc6, 0xaa, 0x8c, 0x6e, 0x38, 0x54, 0x52, 0xb5, 0x0b, 0xe6, 0xad, 0x8c, 0xfa, + 0xe7, 0x36, 0x95, 0x54, 0x2f, 0x03, 0xd3, 0xe3, 0x58, 0x80, 0x29, 0xc1, 0x29, 0xe5, 0xa9, 0x90, + 0x58, 0x6a, 0xac, 0x7f, 0x8d, 0xb0, 0xa6, 0xbc, 0xd6, 0x9b, 0xd4, 0x97, 0xff, 0x3b, 0x87, 0x75, + 0x5c, 0x4c, 0x44, 0x03, 0x2c, 0x16, 0xe3, 0x2c, 0x2a, 0x85, 0xa3, 0x6e, 0x31, 0xc7, 0x3c, 0x9b, + 0x3b, 0xae, 0x57, 0x33, 0x1f, 0x09, 0xee, 0x19, 0x16, 0xdd, 0xba, 0xc7, 0x84, 0xa0, 0x35, 0x06, + 0x1c, 0xdf, 0xc6, 0x59, 0xd8, 0xec, 0x13, 0x9c, 0xea, 0xa7, 0xd3, 0x38, 0x1b, 0x18, 0x0e, 0xd4, + 0xe7, 0x6b, 0x43, 0xd6, 0x95, 0x6c, 0xaf, 0x5b, 0x4c, 0x2b, 0xb3, 0xdb, 0x87, 0xdd, 0xe2, 0xb4, + 0xeb, 0x44, 0xfe, 0x81, 0x5a, 0xb6, 0xcf, 0xa8, 0xe4, 0x7e, 0xc8, 0xee, 0x5f, 0xa9, 0x05, 0x11, + 0xc8, 0x27, 0x38, 0x13, 0x30, 0xd8, 0xa8, 0x53, 0x51, 0xcf, 0x9d, 0x53, 0xe1, 0xde, 0x39, 0xea, + 0x16, 0x6f, 0xc4, 0xc2, 0x49, 0xe6, 0x39, 0xcc, 0x6f, 0xba, 0x9e, 0x8c, 0x0f, 0x1b, 0x6e, 0x55, + 0x98, 0xd5, 0x8e, 0x64, 0xc2, 0x58, 0x63, 0xdb, 0x95, 0x60, 0x60, 0xcd, 0x05, 0xa1, 0xd6, 0xa8, + 0xa8, 0x93, 0x8b, 0x38, 0x2d, 0x78, 0xdb, 0xb7, 0x59, 0x2e, 0xb5, 0x80, 0x4a, 0x19, 0x0b, 0x66, + 0x24, 0x87, 0x67, 0xab, 0x6d, 0xb7, 0xe1, 0x30, 0x3f, 0x37, 0xa3, 0x16, 0xa2, 0xa9, 0xfe, 0x05, + 0xc2, 0x2f, 0xc7, 0x34, 0x04, 0x59, 0x3e, 0xc2, 0x99, 0x50, 0x96, 0xa0, 0x2a, 0x21, 0x55, 0x95, + 0xae, 0x26, 0x16, 0x88, 0x41, 0x49, 0x63, 0x95, 0x69, 0xce, 0x86, 0x35, 0x52, 0x80, 0x57, 0x1b, + 0x0a, 0x37, 0x77, 0xd8, 0x2d, 0xaa, 0x39, 0xbc, 0xc6, 0x2a, 0x26, 0x7d, 0x08, 0xa2, 0x8f, 0xe1, + 0x43, 0x8c, 0xfb, 0x18, 0xa2, 0x23, 0x3c, 0x31, 0x88, 0xf0, 0x34, 0x67, 0x22, 0x00, 0x62, 0xf9, + 0x5b, 0x8c, 0x67, 0x54, 0x12, 0xf2, 0x1d, 0x1a, 0xac, 0xba, 0x24, 0xa9, 0xcd, 0x24, 0x7d, 0x3f, + 0xe4, 0x17, 0x27, 0x77, 0x08, 0xe1, 0xe8, 0xa5, 0x2f, 0x7f, 0xff, 0xfb, 0xe9, 0xb4, 0x4e, 0x16, + 0xc2, 0x4f, 0x1e, 0x70, 0x30, 0xa3, 0xea, 0x69, 0xee, 0xc0, 0x29, 0xda, 0x25, 0x3f, 0x22, 0xfc, + 0xd2, 0x50, 0x83, 0x24, 0xcb, 0x93, 0xe4, 0x1b, 0xec, 0xdc, 0xf9, 0xf2, 0xa9, 0x7c, 0x00, 0xe6, + 0xa2, 0x82, 0xf9, 0x16, 0x29, 0x8d, 0x83, 0x69, 0xd6, 0x01, 0xda, 0x0f, 0x31, 0xb8, 0xd0, 0x6a, + 0x26, 0x83, 0x3b, 0xd8, 0x8b, 0x27, 0x83, 0x3b, 0xd4, 0xcb, 0x74, 0x43, 0xc1, 0x2d, 0x91, 0x37, + 0x87, 0xe1, 0x3a, 0xcc, 0xdc, 0x81, 0x63, 0xbd, 0xdb, 0x47, 0x2f, 0xc8, 0x4f, 0x08, 0x67, 0x87, + 0xbb, 0x05, 0x19, 0x99, 0x39, 0xa1, 0x91, 0xe5, 0x6f, 0x9c, 0xce, 0x69, 0x1c, 0xde, 0x63, 0xf2, + 0x0a, 0x05, 0xed, 0x67, 0x84, 0xb3, 0xc3, 0x35, 0x7f, 0x34, 0xde, 0x84, 0x6e, 0x35, 0x1a, 0x6f, + 0x52, 0x5b, 0xd1, 0xdf, 0x55, 0x78, 0xcb, 0x64, 0x69, 0x2c, 0x5e, 0x9f, 0x6e, 0x99, 0x3b, 0xcf, + 0xca, 0xff, 0x2e, 0xf9, 0x0d, 0x61, 0x72, 0xbc, 0xd4, 0x93, 0x9b, 0xa3, 0x70, 0x24, 0x36, 0xaa, + 0xfc, 0xad, 0xd3, 0xba, 0x01, 0x81, 0xf7, 0x15, 0x81, 0x9b, 0xa4, 0x3c, 0x5e, 0xf0, 0x20, 0xc8, + 0x20, 0x85, 0xcf, 0x71, 0x4a, 0x6d, 0xe7, 0xab, 0xa3, 0xb7, 0xe6, 0xb3, 0x3d, 0x5c, 0x1a, 0x6f, + 0x08, 0xb8, 0xde, 0x50, 0xb8, 0x34, 0x52, 0x18, 0xb5, 0x71, 0xc9, 0x26, 0x9e, 0x51, 0x15, 0x91, + 0x5c, 0x34, 0xc2, 0xab, 0x8e, 0x11, 0xdd, 0x83, 0x8c, 0x3b, 0xc1, 0x3d, 0x28, 0x7f, 0x6d, 0x5c, + 0xc2, 0x7e, 0x31, 0xd5, 0xf3, 0x2a, 0xe3, 0x05, 0x42, 0x8e, 0x67, 0xac, 0x58, 0x7b, 0x7f, 0x69, + 0x53, 0xdf, 0xf7, 0x34, 0xb4, 0xd7, 0xd3, 0xd0, 0x7e, 0x4f, 0x43, 0x7f, 0xf6, 0x34, 0xf4, 0xcd, + 0x81, 0x36, 0xb5, 0x7f, 0xa0, 0x4d, 0xfd, 0x71, 0xa0, 0x4d, 0x7d, 0xba, 0x18, 0x6b, 0x4b, 0xab, + 0x5c, 0x34, 0x1f, 0x04, 0x31, 0x54, 0x4e, 0x73, 0x1b, 0x9e, 0x83, 0xb7, 0xb8, 0x6a, 0x5a, 0x41, + 0x2d, 0xff, 0x13, 0x00, 0x00, 0xff, 0xff, 0xb6, 0x67, 0xf5, 0xed, 0x35, 0x0e, 0x00, 0x00, +} + +func (this *QueryContractInfoRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractInfoRequest) + if !ok { + that2, ok := that.(QueryContractInfoRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + return true +} +func (this *QueryContractInfoResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractInfoResponse) + if !ok { + that2, ok := that.(QueryContractInfoResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + if !this.ContractInfo.Equal(that1.ContractInfo) { + return false + } + return true +} +func (this *QueryContractHistoryRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractHistoryRequest) + if !ok { + that2, ok := that.(QueryContractHistoryRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + return true +} +func (this *QueryContractHistoryResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractHistoryResponse) + if !ok { + that2, ok := that.(QueryContractHistoryResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.Entries) != len(that1.Entries) { + return false + } + for i := range this.Entries { + if !this.Entries[i].Equal(&that1.Entries[i]) { + return false + } + } + return true +} +func (this *QueryContractsByCodeRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractsByCodeRequest) + if !ok { + that2, ok := that.(QueryContractsByCodeRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.CodeId != that1.CodeId { + return false + } + return true +} +func (this *ContractInfoWithAddress) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ContractInfoWithAddress) + if !ok { + that2, ok := that.(ContractInfoWithAddress) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + if !this.ContractInfo.Equal(that1.ContractInfo) { + return false + } + return true +} +func (this *QueryContractsByCodeResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryContractsByCodeResponse) + if !ok { + that2, ok := that.(QueryContractsByCodeResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.ContractInfos) != len(that1.ContractInfos) { + return false + } + for i := range this.ContractInfos { + if !this.ContractInfos[i].Equal(&that1.ContractInfos[i]) { + return false + } + } + return true +} +func (this *QueryAllContractStateRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryAllContractStateRequest) + if !ok { + that2, ok := that.(QueryAllContractStateRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + return true +} +func (this *QueryAllContractStateResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryAllContractStateResponse) + if !ok { + that2, ok := that.(QueryAllContractStateResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.Models) != len(that1.Models) { + return false + } + for i := range this.Models { + if !this.Models[i].Equal(&that1.Models[i]) { + return false + } + } + return true +} +func (this *QueryRawContractStateRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryRawContractStateRequest) + if !ok { + that2, ok := that.(QueryRawContractStateRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + if !bytes.Equal(this.QueryData, that1.QueryData) { + return false + } + return true +} +func (this *QueryRawContractStateResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryRawContractStateResponse) + if !ok { + that2, ok := that.(QueryRawContractStateResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Data, that1.Data) { + return false + } + return true +} +func (this *QuerySmartContractStateRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QuerySmartContractStateRequest) + if !ok { + that2, ok := that.(QuerySmartContractStateRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + if !bytes.Equal(this.QueryData, that1.QueryData) { + return false + } + return true +} +func (this *QuerySmartContractStateResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QuerySmartContractStateResponse) + if !ok { + that2, ok := that.(QuerySmartContractStateResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Data, that1.Data) { + return false + } + return true +} +func (this *QueryCodeRequest) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryCodeRequest) + if !ok { + that2, ok := that.(QueryCodeRequest) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.CodeId != that1.CodeId { + return false + } + return true +} +func (this *CodeInfoResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*CodeInfoResponse) + if !ok { + that2, ok := that.(CodeInfoResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.CodeID != that1.CodeID { + return false + } + if !bytes.Equal(this.Creator, that1.Creator) { + return false + } + if !bytes.Equal(this.DataHash, that1.DataHash) { + return false + } + if this.Source != that1.Source { + return false + } + if this.Builder != that1.Builder { + return false + } + return true +} +func (this *QueryCodeResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryCodeResponse) + if !ok { + that2, ok := that.(QueryCodeResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !this.CodeInfoResponse.Equal(that1.CodeInfoResponse) { + return false + } + if !bytes.Equal(this.Data, that1.Data) { + return false + } + return true +} +func (this *QueryCodesResponse) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*QueryCodesResponse) + if !ok { + that2, ok := that.(QueryCodesResponse) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.CodeInfos) != len(that1.CodeInfos) { + return false + } + for i := range this.CodeInfos { + if !this.CodeInfos[i].Equal(&that1.CodeInfos[i]) { + return false + } + } + return true +} + +// Reference imports to suppress errors if they are not otherwise used. +var _ context.Context +var _ grpc.ClientConn + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +const _ = grpc.SupportPackageIsVersion4 + +// QueryClient is the client API for Query service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. +type QueryClient interface { + ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) + ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) + ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) + AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) + RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) + SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) + Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) + Codes(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*QueryCodesResponse, error) +} + +type queryClient struct { + cc grpc1.ClientConn +} + +func NewQueryClient(cc grpc1.ClientConn) QueryClient { + return &queryClient{cc} +} + +func (c *queryClient) ContractInfo(ctx context.Context, in *QueryContractInfoRequest, opts ...grpc.CallOption) (*QueryContractInfoResponse, error) { + out := new(QueryContractInfoResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/ContractInfo", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ContractHistory(ctx context.Context, in *QueryContractHistoryRequest, opts ...grpc.CallOption) (*QueryContractHistoryResponse, error) { + out := new(QueryContractHistoryResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/ContractHistory", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) ContractsByCode(ctx context.Context, in *QueryContractsByCodeRequest, opts ...grpc.CallOption) (*QueryContractsByCodeResponse, error) { + out := new(QueryContractsByCodeResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/ContractsByCode", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) AllContractState(ctx context.Context, in *QueryAllContractStateRequest, opts ...grpc.CallOption) (*QueryAllContractStateResponse, error) { + out := new(QueryAllContractStateResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/AllContractState", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) RawContractState(ctx context.Context, in *QueryRawContractStateRequest, opts ...grpc.CallOption) (*QueryRawContractStateResponse, error) { + out := new(QueryRawContractStateResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/RawContractState", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) SmartContractState(ctx context.Context, in *QuerySmartContractStateRequest, opts ...grpc.CallOption) (*QuerySmartContractStateResponse, error) { + out := new(QuerySmartContractStateResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/SmartContractState", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Code(ctx context.Context, in *QueryCodeRequest, opts ...grpc.CallOption) (*QueryCodeResponse, error) { + out := new(QueryCodeResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/Code", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *queryClient) Codes(ctx context.Context, in *empty.Empty, opts ...grpc.CallOption) (*QueryCodesResponse, error) { + out := new(QueryCodesResponse) + err := c.cc.Invoke(ctx, "/wasmd.x.wasmd.v1beta1.Query/Codes", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// QueryServer is the server API for Query service. +type QueryServer interface { + ContractInfo(context.Context, *QueryContractInfoRequest) (*QueryContractInfoResponse, error) + ContractHistory(context.Context, *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) + ContractsByCode(context.Context, *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) + AllContractState(context.Context, *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) + RawContractState(context.Context, *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) + SmartContractState(context.Context, *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) + Code(context.Context, *QueryCodeRequest) (*QueryCodeResponse, error) + Codes(context.Context, *empty.Empty) (*QueryCodesResponse, error) +} + +// UnimplementedQueryServer can be embedded to have forward compatible implementations. +type UnimplementedQueryServer struct { +} + +func (*UnimplementedQueryServer) ContractInfo(ctx context.Context, req *QueryContractInfoRequest) (*QueryContractInfoResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ContractInfo not implemented") +} +func (*UnimplementedQueryServer) ContractHistory(ctx context.Context, req *QueryContractHistoryRequest) (*QueryContractHistoryResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ContractHistory not implemented") +} +func (*UnimplementedQueryServer) ContractsByCode(ctx context.Context, req *QueryContractsByCodeRequest) (*QueryContractsByCodeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ContractsByCode not implemented") +} +func (*UnimplementedQueryServer) AllContractState(ctx context.Context, req *QueryAllContractStateRequest) (*QueryAllContractStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method AllContractState not implemented") +} +func (*UnimplementedQueryServer) RawContractState(ctx context.Context, req *QueryRawContractStateRequest) (*QueryRawContractStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method RawContractState not implemented") +} +func (*UnimplementedQueryServer) SmartContractState(ctx context.Context, req *QuerySmartContractStateRequest) (*QuerySmartContractStateResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method SmartContractState not implemented") +} +func (*UnimplementedQueryServer) Code(ctx context.Context, req *QueryCodeRequest) (*QueryCodeResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Code not implemented") +} +func (*UnimplementedQueryServer) Codes(ctx context.Context, req *empty.Empty) (*QueryCodesResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method Codes not implemented") +} + +func RegisterQueryServer(s grpc1.Server, srv QueryServer) { + s.RegisterService(&_Query_serviceDesc, srv) +} + +func _Query_ContractInfo_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryContractInfoRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ContractInfo(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/ContractInfo", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ContractInfo(ctx, req.(*QueryContractInfoRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ContractHistory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryContractHistoryRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ContractHistory(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/ContractHistory", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ContractHistory(ctx, req.(*QueryContractHistoryRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_ContractsByCode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryContractsByCodeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).ContractsByCode(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/ContractsByCode", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).ContractsByCode(ctx, req.(*QueryContractsByCodeRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_AllContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryAllContractStateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).AllContractState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/AllContractState", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).AllContractState(ctx, req.(*QueryAllContractStateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_RawContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryRawContractStateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).RawContractState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/RawContractState", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).RawContractState(ctx, req.(*QueryRawContractStateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_SmartContractState_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QuerySmartContractStateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).SmartContractState(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/SmartContractState", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).SmartContractState(ctx, req.(*QuerySmartContractStateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Code_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(QueryCodeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Code(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/Code", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Code(ctx, req.(*QueryCodeRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Query_Codes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(empty.Empty) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(QueryServer).Codes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/wasmd.x.wasmd.v1beta1.Query/Codes", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(QueryServer).Codes(ctx, req.(*empty.Empty)) + } + return interceptor(ctx, in, info, handler) +} + +var _Query_serviceDesc = grpc.ServiceDesc{ + ServiceName: "wasmd.x.wasmd.v1beta1.Query", + HandlerType: (*QueryServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "ContractInfo", + Handler: _Query_ContractInfo_Handler, + }, + { + MethodName: "ContractHistory", + Handler: _Query_ContractHistory_Handler, + }, + { + MethodName: "ContractsByCode", + Handler: _Query_ContractsByCode_Handler, + }, + { + MethodName: "AllContractState", + Handler: _Query_AllContractState_Handler, + }, + { + MethodName: "RawContractState", + Handler: _Query_RawContractState_Handler, + }, + { + MethodName: "SmartContractState", + Handler: _Query_SmartContractState_Handler, + }, + { + MethodName: "Code", + Handler: _Query_Code_Handler, + }, + { + MethodName: "Codes", + Handler: _Query_Codes_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "x/wasm/internal/types/query.proto", +} + +func (m *QueryContractInfoRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractInfoRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractInfoRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryContractInfoResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractInfoResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ContractInfo != nil { + { + size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryContractHistoryRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractHistoryRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractHistoryRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryContractHistoryResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractHistoryResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractHistoryResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Entries) > 0 { + for iNdEx := len(m.Entries) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Entries[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryContractsByCodeRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractsByCodeRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractsByCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.CodeId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ContractInfoWithAddress) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ContractInfoWithAddress) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ContractInfoWithAddress) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.ContractInfo != nil { + { + size, err := m.ContractInfo.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryContractsByCodeResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryContractsByCodeResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryContractsByCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.ContractInfos) > 0 { + for iNdEx := len(m.ContractInfos) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.ContractInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryAllContractStateRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAllContractStateRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAllContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryAllContractStateResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryAllContractStateResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryAllContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Models) > 0 { + for iNdEx := len(m.Models) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Models[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *QueryRawContractStateRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryRawContractStateRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRawContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.QueryData) > 0 { + i -= len(m.QueryData) + copy(dAtA[i:], m.QueryData) + i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) + i-- + dAtA[i] = 0x12 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryRawContractStateResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryRawContractStateResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryRawContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QuerySmartContractStateRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QuerySmartContractStateRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySmartContractStateRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.QueryData) > 0 { + i -= len(m.QueryData) + copy(dAtA[i:], m.QueryData) + i = encodeVarintQuery(dAtA, i, uint64(len(m.QueryData))) + i-- + dAtA[i] = 0x12 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QuerySmartContractStateResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QuerySmartContractStateResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QuerySmartContractStateResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryCodeRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryCodeRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCodeRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.CodeId != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.CodeId)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *CodeInfoResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CodeInfoResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CodeInfoResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Builder) > 0 { + i -= len(m.Builder) + copy(dAtA[i:], m.Builder) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Builder))) + i-- + dAtA[i] = 0x2a + } + if len(m.Source) > 0 { + i -= len(m.Source) + copy(dAtA[i:], m.Source) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Source))) + i-- + dAtA[i] = 0x22 + } + if len(m.DataHash) > 0 { + i -= len(m.DataHash) + copy(dAtA[i:], m.DataHash) + i = encodeVarintQuery(dAtA, i, uint64(len(m.DataHash))) + i-- + dAtA[i] = 0x1a + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0x12 + } + if m.CodeID != 0 { + i = encodeVarintQuery(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *QueryCodeResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryCodeResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCodeResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Data) > 0 { + i -= len(m.Data) + copy(dAtA[i:], m.Data) + i = encodeVarintQuery(dAtA, i, uint64(len(m.Data))) + i-- + dAtA[i] = 0x12 + } + if m.CodeInfoResponse != nil { + { + size, err := m.CodeInfoResponse.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *QueryCodesResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *QueryCodesResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *QueryCodesResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CodeInfos) > 0 { + for iNdEx := len(m.CodeInfos) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CodeInfos[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintQuery(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func encodeVarintQuery(dAtA []byte, offset int, v uint64) int { + offset -= sovQuery(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *QueryContractInfoRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryContractInfoResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if m.ContractInfo != nil { + l = m.ContractInfo.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryContractHistoryRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryContractHistoryResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Entries) > 0 { + for _, e := range m.Entries { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryContractsByCodeRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeId != 0 { + n += 1 + sovQuery(uint64(m.CodeId)) + } + return n +} + +func (m *ContractInfoWithAddress) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + if m.ContractInfo != nil { + l = m.ContractInfo.Size() + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryContractsByCodeResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.ContractInfos) > 0 { + for _, e := range m.ContractInfos { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryAllContractStateRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryAllContractStateResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.Models) > 0 { + for _, e := range m.Models { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func (m *QueryRawContractStateRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.QueryData) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryRawContractStateResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Data) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QuerySmartContractStateRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.QueryData) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QuerySmartContractStateResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Data) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryCodeRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeId != 0 { + n += 1 + sovQuery(uint64(m.CodeId)) + } + return n +} + +func (m *CodeInfoResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeID != 0 { + n += 1 + sovQuery(uint64(m.CodeID)) + } + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.DataHash) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Source) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Builder) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryCodeResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeInfoResponse != nil { + l = m.CodeInfoResponse.Size() + n += 1 + l + sovQuery(uint64(l)) + } + l = len(m.Data) + if l > 0 { + n += 1 + l + sovQuery(uint64(l)) + } + return n +} + +func (m *QueryCodesResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.CodeInfos) > 0 { + for _, e := range m.CodeInfos { + l = e.Size() + n += 1 + l + sovQuery(uint64(l)) + } + } + return n +} + +func sovQuery(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozQuery(x uint64) (n int) { + return sovQuery(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *QueryContractInfoRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractInfoRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractInfoRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryContractInfoResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractInfoResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ContractInfo == nil { + m.ContractInfo = &ContractInfo{} + } + if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryContractHistoryRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractHistoryRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractHistoryRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryContractHistoryResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractHistoryResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractHistoryResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Entries", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Entries = append(m.Entries, ContractCodeHistoryEntry{}) + if err := m.Entries[len(m.Entries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryContractsByCodeRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractsByCodeRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractsByCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) + } + m.CodeId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ContractInfoWithAddress) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ContractInfoWithAddress: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ContractInfoWithAddress: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractInfo", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.ContractInfo == nil { + m.ContractInfo = &ContractInfo{} + } + if err := m.ContractInfo.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryContractsByCodeResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryContractsByCodeResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryContractsByCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ContractInfos", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ContractInfos = append(m.ContractInfos, ContractInfoWithAddress{}) + if err := m.ContractInfos[len(m.ContractInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAllContractStateRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAllContractStateRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAllContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryAllContractStateResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryAllContractStateResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryAllContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Models", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Models = append(m.Models, Model{}) + if err := m.Models[len(m.Models)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryRawContractStateRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryRawContractStateRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRawContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) + if m.QueryData == nil { + m.QueryData = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryRawContractStateResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryRawContractStateResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryRawContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySmartContractStateRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySmartContractStateRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySmartContractStateRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field QueryData", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.QueryData = append(m.QueryData[:0], dAtA[iNdEx:postIndex]...) + if m.QueryData == nil { + m.QueryData = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QuerySmartContractStateResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QuerySmartContractStateResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QuerySmartContractStateResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryCodeRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryCodeRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCodeRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeId", wireType) + } + m.CodeId = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeId |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CodeInfoResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CodeInfoResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CodeInfoResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = append(m.Creator[:0], dAtA[iNdEx:postIndex]...) + if m.Creator == nil { + m.Creator = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field DataHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.DataHash = append(m.DataHash[:0], dAtA[iNdEx:postIndex]...) + if m.DataHash == nil { + m.DataHash = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Source = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Builder = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryCodeResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryCodeResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCodeResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeInfoResponse", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.CodeInfoResponse == nil { + m.CodeInfoResponse = &CodeInfoResponse{} + } + if err := m.CodeInfoResponse.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Data = append(m.Data[:0], dAtA[iNdEx:postIndex]...) + if m.Data == nil { + m.Data = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *QueryCodesResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: QueryCodesResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: QueryCodesResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeInfos", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowQuery + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthQuery + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthQuery + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CodeInfos = append(m.CodeInfos, CodeInfoResponse{}) + if err := m.CodeInfos[len(m.CodeInfos)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipQuery(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthQuery + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipQuery(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowQuery + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthQuery + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupQuery + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthQuery + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthQuery = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowQuery = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupQuery = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/wasm/internal/types/query.pb.gw.go b/x/wasm/internal/types/query.pb.gw.go new file mode 100644 index 0000000000..9335f0fb6c --- /dev/null +++ b/x/wasm/internal/types/query.pb.gw.go @@ -0,0 +1,905 @@ +// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT. +// source: x/wasm/internal/types/query.proto + +/* +Package types is a reverse proxy. + +It translates gRPC into RESTful JSON APIs. +*/ +package types + +import ( + "context" + "io" + "net/http" + + "github.com/golang/protobuf/descriptor" + "github.com/golang/protobuf/proto" + "github.com/golang/protobuf/ptypes/empty" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/grpc-ecosystem/grpc-gateway/utilities" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/grpclog" + "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" +) + +// Suppress "imported and not used" errors +var _ codes.Code +var _ io.Reader +var _ status.Status +var _ = runtime.String +var _ = utilities.NewDoubleArray +var _ = descriptor.ForMessage +var _ = metadata.Join + +func request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractInfoRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := client.ContractInfo(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ContractInfo_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractInfoRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := server.ContractInfo(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractHistoryRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := client.ContractHistory(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ContractHistory_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractHistoryRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := server.ContractHistory(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractsByCodeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["code_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") + } + + protoReq.CodeId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) + } + + msg, err := client.ContractsByCode(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_ContractsByCode_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryContractsByCodeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["code_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") + } + + protoReq.CodeId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) + } + + msg, err := server.ContractsByCode(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := client.AllContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_AllContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryAllContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + msg, err := server.AllContractState(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRawContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + val, ok = pathParams["query_data"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") + } + + protoReq.QueryData, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) + } + + msg, err := client.RawContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_RawContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryRawContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + val, ok = pathParams["query_data"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") + } + + protoReq.QueryData, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) + } + + msg, err := server.RawContractState(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySmartContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + val, ok = pathParams["query_data"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") + } + + protoReq.QueryData, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) + } + + msg, err := client.SmartContractState(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_SmartContractState_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QuerySmartContractStateRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["address"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "address") + } + + protoReq.Address, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "address", err) + } + + val, ok = pathParams["query_data"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "query_data") + } + + protoReq.QueryData, err = runtime.Bytes(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "query_data", err) + } + + msg, err := server.SmartContractState(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCodeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["code_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") + } + + protoReq.CodeId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) + } + + msg, err := client.Code(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Code_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq QueryCodeRequest + var metadata runtime.ServerMetadata + + var ( + val string + ok bool + err error + _ = err + ) + + val, ok = pathParams["code_id"] + if !ok { + return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", "code_id") + } + + protoReq.CodeId, err = runtime.Uint64(val) + + if err != nil { + return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", "code_id", err) + } + + msg, err := server.Code(ctx, &protoReq) + return msg, metadata, err + +} + +func request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, client QueryClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq empty.Empty + var metadata runtime.ServerMetadata + + msg, err := client.Codes(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD)) + return msg, metadata, err + +} + +func local_request_Query_Codes_0(ctx context.Context, marshaler runtime.Marshaler, server QueryServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) { + var protoReq empty.Empty + var metadata runtime.ServerMetadata + + msg, err := server.Codes(ctx, &protoReq) + return msg, metadata, err + +} + +// RegisterQueryHandlerServer registers the http handlers for service Query to "mux". +// UnaryRPC :call QueryServer directly. +// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906. +// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterQueryHandlerFromEndpoint instead. +func RegisterQueryHandlerServer(ctx context.Context, mux *runtime.ServeMux, server QueryServer) error { + + mux.Handle("GET", pattern_Query_ContractInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ContractInfo_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ContractHistory_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ContractHistory_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ContractsByCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_ContractsByCode_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AllContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_AllContractState_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_RawContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_RawContractState_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SmartContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_SmartContractState_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Code_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Code_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Codes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + var stream runtime.ServerTransportStream + ctx = grpc.NewContextWithServerTransportStream(ctx, &stream) + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := local_request_Query_Codes_0(rctx, inboundMarshaler, server, req, pathParams) + md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer()) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +// RegisterQueryHandlerFromEndpoint is same as RegisterQueryHandler but +// automatically dials to "endpoint" and closes the connection when "ctx" gets done. +func RegisterQueryHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) { + conn, err := grpc.Dial(endpoint, opts...) + if err != nil { + return err + } + defer func() { + if err != nil { + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + return + } + go func() { + <-ctx.Done() + if cerr := conn.Close(); cerr != nil { + grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr) + } + }() + }() + + return RegisterQueryHandler(ctx, mux, conn) +} + +// RegisterQueryHandler registers the http handlers for service Query to "mux". +// The handlers forward requests to the grpc endpoint over "conn". +func RegisterQueryHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error { + return RegisterQueryHandlerClient(ctx, mux, NewQueryClient(conn)) +} + +// RegisterQueryHandlerClient registers the http handlers for service Query +// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "QueryClient". +// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "QueryClient" +// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in +// "QueryClient" to call the correct interceptors. +func RegisterQueryHandlerClient(ctx context.Context, mux *runtime.ServeMux, client QueryClient) error { + + mux.Handle("GET", pattern_Query_ContractInfo_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ContractInfo_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractInfo_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ContractHistory_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ContractHistory_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractHistory_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_ContractsByCode_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_ContractsByCode_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_ContractsByCode_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_AllContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_AllContractState_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_AllContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_RawContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_RawContractState_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_RawContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_SmartContractState_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_SmartContractState_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_SmartContractState_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Code_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Code_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Code_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + mux.Handle("GET", pattern_Query_Codes_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) { + ctx, cancel := context.WithCancel(req.Context()) + defer cancel() + inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req) + rctx, err := runtime.AnnotateContext(ctx, mux, req) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + resp, md, err := request_Query_Codes_0(rctx, inboundMarshaler, client, req, pathParams) + ctx = runtime.NewServerMetadataContext(ctx, md) + if err != nil { + runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err) + return + } + + forward_Query_Codes_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...) + + }) + + return nil +} + +var ( + pattern_Query_ContractInfo_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"wasm", "v1beta1", "contract", "address"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_ContractHistory_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"wasm", "v1beta1", "contract", "address", "history"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_ContractsByCode_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"wasm", "v1beta1", "code", "code_id", "contracts"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_AllContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4}, []string{"wasm", "v1beta1", "contract", "address", "state"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_RawContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"wasm", "v1beta1", "contract", "address", "raw", "query_data"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_SmartContractState_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3, 2, 4, 1, 0, 4, 1, 5, 5}, []string{"wasm", "v1beta1", "contract", "address", "smart", "query_data"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_Code_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"wasm", "v1beta1", "code", "code_id"}, "", runtime.AssumeColonVerbOpt(true))) + + pattern_Query_Codes_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"wasm", "v1beta1", "code"}, "", runtime.AssumeColonVerbOpt(true))) +) + +var ( + forward_Query_ContractInfo_0 = runtime.ForwardResponseMessage + + forward_Query_ContractHistory_0 = runtime.ForwardResponseMessage + + forward_Query_ContractsByCode_0 = runtime.ForwardResponseMessage + + forward_Query_AllContractState_0 = runtime.ForwardResponseMessage + + forward_Query_RawContractState_0 = runtime.ForwardResponseMessage + + forward_Query_SmartContractState_0 = runtime.ForwardResponseMessage + + forward_Query_Code_0 = runtime.ForwardResponseMessage + + forward_Query_Codes_0 = runtime.ForwardResponseMessage +) diff --git a/x/wasm/internal/types/query.proto b/x/wasm/internal/types/query.proto new file mode 100644 index 0000000000..c861f877eb --- /dev/null +++ b/x/wasm/internal/types/query.proto @@ -0,0 +1,124 @@ +syntax = "proto3"; +package wasmd.x.wasmd.v1beta1; + +import "gogoproto/gogo.proto"; +import "x/wasm/internal/types/types.proto"; +import "google/protobuf/empty.proto"; +import "google/api/annotations.proto"; + +option go_package = "github.com/CosmWasm/wasmd/x/wasmd/internal/types"; +option (gogoproto.goproto_getters_all) = false; +option (gogoproto.equal_all) = true; + +// Query provides defines the gRPC querier service +service Query { + rpc ContractInfo (QueryContractInfoRequest) returns (QueryContractInfoResponse) { + option (google.api.http).get = "/wasm/v1beta1/contract/{address}"; + } + rpc ContractHistory (QueryContractHistoryRequest) returns (QueryContractHistoryResponse) { + option (google.api.http).get = "/wasm/v1beta1/contract/{address}/history"; + } + rpc ContractsByCode (QueryContractsByCodeRequest) returns (QueryContractsByCodeResponse) { + option (google.api.http).get = "/wasm/v1beta1/code/{code_id}/contracts"; + } + rpc AllContractState (QueryAllContractStateRequest) returns (QueryAllContractStateResponse) { + option (google.api.http).get = "/wasm/v1beta1/contract/{address}/state"; + } + rpc RawContractState (QueryRawContractStateRequest) returns (QueryRawContractStateResponse) { + option (google.api.http).get = "/wasm/v1beta1/contract/{address}/raw/{query_data}"; + } + rpc SmartContractState (QuerySmartContractStateRequest) returns (QuerySmartContractStateResponse) { + option (google.api.http).get = "/wasm/v1beta1/contract/{address}/smart/{query_data}"; + } + rpc Code (QueryCodeRequest) returns (QueryCodeResponse) { + option (google.api.http).get = "/wasm/v1beta1/code/{code_id}"; + } + rpc Codes (google.protobuf.Empty) returns (QueryCodesResponse) { + option (google.api.http).get = "/wasm/v1beta1/code"; + } +} + +// QueryContractInfoRequest is the request type for the Query/ContractInfo RPC method +message QueryContractInfoRequest { + // address is the address of the contract to query + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} +// QueryContractInfoResponse is the response type for the Query/ContractInfo RPC method +message QueryContractInfoResponse { + // address is the address of the contract + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + ContractInfo ContractInfo = 2 [(gogoproto.embed) = true, (gogoproto.jsontag) = ""]; +} + +message QueryContractHistoryRequest { + // address is the address of the contract to query + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} + +message QueryContractHistoryResponse { + repeated ContractCodeHistoryEntry entries = 1 [(gogoproto.nullable) = false]; +} + +message QueryContractsByCodeRequest { + uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID +} + +// ContractInfoWithAddress adds the address (key) to the ContractInfo representation +message ContractInfoWithAddress { + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + ContractInfo ContractInfo = 2 [(gogoproto.embed) = true, (gogoproto.jsontag) = ""]; +} + +message QueryContractsByCodeResponse { + repeated ContractInfoWithAddress contract_infos = 1 [(gogoproto.nullable) = false]; +} + +message QueryAllContractStateRequest { + // address is the address of the contract + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; +} + +message QueryAllContractStateResponse { + repeated Model models = 1 [(gogoproto.nullable) = false]; +} + +message QueryRawContractStateRequest { + // address is the address of the contract + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes query_data = 2; +} + +message QueryRawContractStateResponse { + bytes data = 1; +} + +message QuerySmartContractStateRequest { + // address is the address of the contract + bytes address = 1 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes query_data = 2; +} + +message QuerySmartContractStateResponse { + bytes data = 1 [(gogoproto.casttype) = "encoding/json.RawMessage"]; +} + +message QueryCodeRequest { + uint64 code_id = 1; // grpc-gateway_out does not support Go style CodID +} + +message CodeInfoResponse { + uint64 code_id = 1 [(gogoproto.customname) = "CodeID", (gogoproto.jsontag) = "id"]; // id for legacy support + bytes creator = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes data_hash = 3 [(gogoproto.casttype) = "github.com/tendermint/tendermint/libs/bytes.HexBytes"]; + string source = 4; + string builder = 5; +} + +message QueryCodeResponse { + CodeInfoResponse code_info = 1 [(gogoproto.embed) = true, (gogoproto.jsontag) = ""]; + bytes data = 2 [(gogoproto.jsontag) = "data"]; +} + +message QueryCodesResponse { + repeated CodeInfoResponse code_infos = 1 [(gogoproto.nullable) = false]; +} diff --git a/x/wasm/internal/types/test_fixtures.go b/x/wasm/internal/types/test_fixtures.go index 60b1e683f6..7063c36dbf 100644 --- a/x/wasm/internal/types/test_fixtures.go +++ b/x/wasm/internal/types/test_fixtures.go @@ -4,9 +4,9 @@ import ( "bytes" "crypto/sha256" "encoding/json" + "math/rand" sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/tendermint/tendermint/libs/rand" ) func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { @@ -30,7 +30,7 @@ func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { } for i := 0; i < numSequences; i++ { fixture.Sequences[i] = Sequence{ - IDKey: rand.Bytes(5), + IDKey: randBytes(5), Value: uint64(i), } } @@ -40,13 +40,19 @@ func GenesisFixture(mutators ...func(*GenesisState)) GenesisState { return fixture } +func randBytes(n int) []byte { + r := make([]byte, n) + rand.Read(r) + return r +} + func CodeFixture(mutators ...func(*Code)) Code { - wasmCode := rand.Bytes(100) + wasmCode := randBytes(100) fixture := Code{ - CodeID: 1, - CodeInfo: CodeInfoFixture(WithSHA256CodeHash(wasmCode)), - CodesBytes: wasmCode, + CodeID: 1, + CodeInfo: CodeInfoFixture(WithSHA256CodeHash(wasmCode)), + CodeBytes: wasmCode, } for _, m := range mutators { @@ -112,25 +118,23 @@ func WithSHA256CodeHash(wasmCode []byte) func(info *CodeInfo) { } } -func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) StoreCodeProposal { +func StoreCodeProposalFixture(mutators ...func(*StoreCodeProposal)) *StoreCodeProposal { var anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) - p := StoreCodeProposal{ - WasmProposal: WasmProposal{ - Title: "Foo", - Description: "Bar", - }, + p := &StoreCodeProposal{ + Title: "Foo", + Description: "Bar", RunAs: anyValidAddress, WASMByteCode: []byte{0x0}, Source: "https://example.com/code", Builder: "foo/bar:latest", } for _, m := range mutators { - m(&p) + m(p) } return p } -func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) InstantiateContractProposal { +func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractProposal)) *InstantiateContractProposal { var ( anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) @@ -147,26 +151,24 @@ func InstantiateContractProposalFixture(mutators ...func(p *InstantiateContractP if err != nil { panic(err) } - p := InstantiateContractProposal{ - WasmProposal: WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - RunAs: anyValidAddress, - Admin: anyValidAddress, - CodeID: 1, - Label: "testing", - InitMsg: initMsgBz, - InitFunds: nil, + p := &InstantiateContractProposal{ + Title: "Foo", + Description: "Bar", + RunAs: anyValidAddress, + Admin: anyValidAddress, + CodeID: 1, + Label: "testing", + InitMsg: initMsgBz, + InitFunds: nil, } for _, m := range mutators { - m(&p) + m(p) } return p } -func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) MigrateContractProposal { +func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal)) *MigrateContractProposal { var ( anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) @@ -184,24 +186,22 @@ func MigrateContractProposalFixture(mutators ...func(p *MigrateContractProposal) panic(err) } - p := MigrateContractProposal{ - WasmProposal: WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, - CodeID: 1, - MigrateMsg: migMsgBz, - RunAs: anyValidAddress, + p := &MigrateContractProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, + CodeID: 1, + MigrateMsg: migMsgBz, + RunAs: anyValidAddress, } for _, m := range mutators { - m(&p) + m(p) } return p } -func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) UpdateAdminProposal { +func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) *UpdateAdminProposal { var anyValidAddress sdk.AccAddress = bytes.Repeat([]byte{0x1}, sdk.AddrLen) contractAddr, err := sdk.AccAddressFromBech32("cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5") @@ -209,35 +209,31 @@ func UpdateAdminProposalFixture(mutators ...func(p *UpdateAdminProposal)) Update panic(err) } - p := UpdateAdminProposal{ - WasmProposal: WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - NewAdmin: anyValidAddress, - Contract: contractAddr, + p := &UpdateAdminProposal{ + Title: "Foo", + Description: "Bar", + NewAdmin: anyValidAddress, + Contract: contractAddr, } for _, m := range mutators { - m(&p) + m(p) } return p } -func ClearAdminProposalFixture(mutators ...func(p *ClearAdminProposal)) ClearAdminProposal { +func ClearAdminProposalFixture(mutators ...func(p *ClearAdminProposal)) *ClearAdminProposal { contractAddr, err := sdk.AccAddressFromBech32("cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5") if err != nil { panic(err) } - p := ClearAdminProposal{ - WasmProposal: WasmProposal{ - Title: "Foo", - Description: "Bar", - }, - Contract: contractAddr, + p := &ClearAdminProposal{ + Title: "Foo", + Description: "Bar", + Contract: contractAddr, } for _, m := range mutators { - m(&p) + m(p) } return p } diff --git a/x/wasm/internal/types/types.go b/x/wasm/internal/types/types.go index 5f9499ab9c..6e2e159730 100644 --- a/x/wasm/internal/types/types.go +++ b/x/wasm/internal/types/types.go @@ -1,26 +1,14 @@ package types import ( - "encoding/json" - - sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" - tmBytes "github.com/tendermint/tendermint/libs/bytes" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) const defaultLRUCacheSize = uint64(0) const defaultQueryGasLimit = uint64(3000000) -// Model is a struct that holds a KV pair -type Model struct { - // hex-encode key to read it better (this is often ascii) - Key tmBytes.HexBytes `json:"key"` - // base64-encode raw value - Value []byte `json:"val"` -} - func (m Model) ValidateBasic() error { if len(m.Key) == 0 { return sdkerrors.Wrap(ErrEmpty, "key") @@ -28,15 +16,6 @@ func (m Model) ValidateBasic() error { return nil } -// CodeInfo is data for the uploaded contract WASM code -type CodeInfo struct { - CodeHash []byte `json:"code_hash"` - Creator sdk.AccAddress `json:"creator"` - Source string `json:"source"` - Builder string `json:"builder"` - InstantiateConfig AccessConfig `json:"instantiate_config"` -} - func (c CodeInfo) ValidateBasic() error { if len(c.CodeHash) == 0 { return sdkerrors.Wrap(ErrEmpty, "code hash") @@ -67,33 +46,10 @@ func NewCodeInfo(codeHash []byte, creator sdk.AccAddress, source string, builder } } -type ContractCodeHistoryOperationType string +var AllCodeHistoryTypes = []ContractCodeHistoryOperationType{ContractCodeHistoryTypeGenesis, ContractCodeHistoryTypeInit, ContractCodeHistoryTypeMigrate} -const ( - InitContractCodeHistoryType ContractCodeHistoryOperationType = "Init" - MigrateContractCodeHistoryType ContractCodeHistoryOperationType = "Migrate" - GenesisContractCodeHistoryType ContractCodeHistoryOperationType = "Genesis" -) - -var AllCodeHistoryTypes = []ContractCodeHistoryOperationType{InitContractCodeHistoryType, MigrateContractCodeHistoryType} - -// ContractCodeHistoryEntry stores code updates to a contract. -type ContractCodeHistoryEntry struct { - Operation ContractCodeHistoryOperationType `json:"operation"` - CodeID uint64 `json:"code_id"` - Updated *AbsoluteTxPosition `json:"updated,omitempty"` - Msg json.RawMessage `json:"msg,omitempty"` -} - -// ContractInfo stores a WASM contract instance -type ContractInfo struct { - CodeID uint64 `json:"code_id"` - Creator sdk.AccAddress `json:"creator"` - Admin sdk.AccAddress `json:"admin,omitempty"` - Label string `json:"label"` - // never show this in query results, just use for sorting - // (Note: when using json tag "-" amino refused to serialize it...) - Created *AbsoluteTxPosition `json:"created,omitempty"` +func (c *ContractHistory) AppendCodeHistory(newEntries ...ContractCodeHistoryEntry) { + c.CodeHistoryEntries = append(c.CodeHistoryEntries, newEntries...) } // NewContractInfo creates a new instance of a given WASM contract info @@ -106,6 +62,7 @@ func NewContractInfo(codeID uint64, creator, admin sdk.AccAddress, label string, Created: createdAt, } } + func (c *ContractInfo) ValidateBasic() error { if c.CodeID == 0 { return sdkerrors.Wrap(ErrEmpty, "code id") @@ -126,7 +83,7 @@ func (c *ContractInfo) ValidateBasic() error { func (c ContractInfo) InitialHistory(initMsg []byte) ContractCodeHistoryEntry { return ContractCodeHistoryEntry{ - Operation: InitContractCodeHistoryType, + Operation: ContractCodeHistoryTypeInit, CodeID: c.CodeID, Updated: c.Created, Msg: initMsg, @@ -135,7 +92,7 @@ func (c ContractInfo) InitialHistory(initMsg []byte) ContractCodeHistoryEntry { func (c *ContractInfo) AddMigration(ctx sdk.Context, codeID uint64, msg []byte) ContractCodeHistoryEntry { h := ContractCodeHistoryEntry{ - Operation: MigrateContractCodeHistoryType, + Operation: ContractCodeHistoryTypeMigrate, CodeID: codeID, Updated: NewAbsoluteTxPosition(ctx), Msg: msg, @@ -148,20 +105,12 @@ func (c *ContractInfo) AddMigration(ctx sdk.Context, codeID uint64, msg []byte) func (c *ContractInfo) ResetFromGenesis(ctx sdk.Context) ContractCodeHistoryEntry { c.Created = NewAbsoluteTxPosition(ctx) return ContractCodeHistoryEntry{ - Operation: GenesisContractCodeHistoryType, + Operation: ContractCodeHistoryTypeGenesis, CodeID: c.CodeID, Updated: c.Created, } } -// AbsoluteTxPosition can be used to sort contracts -type AbsoluteTxPosition struct { - // BlockHeight is the block the contract was created at - BlockHeight int64 - // TxIndex is a monotonic counter within the block (actual transaction index, or gas consumed) - TxIndex uint64 -} - // LessThan can be used to sort func (a *AbsoluteTxPosition) LessThan(b *AbsoluteTxPosition) bool { if a == nil { diff --git a/x/wasm/internal/types/types.pb.go b/x/wasm/internal/types/types.pb.go new file mode 100644 index 0000000000..423b24b3bd --- /dev/null +++ b/x/wasm/internal/types/types.pb.go @@ -0,0 +1,2618 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: x/wasm/internal/types/types.proto + +package types + +import ( + bytes "bytes" + encoding_json "encoding/json" + fmt "fmt" + github_com_cosmos_cosmos_sdk_types "github.com/cosmos/cosmos-sdk/types" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/gogo/protobuf/proto" + github_com_tendermint_tendermint_libs_bytes "github.com/tendermint/tendermint/libs/bytes" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.GoGoProtoPackageIsVersion3 // please upgrade the proto package + +type AccessType int32 + +const ( + AccessTypeUndefined AccessType = 0 + AccessTypeNobody AccessType = 1 + AccessTypeOnlyAddress AccessType = 2 + AccessTypeEverybody AccessType = 3 +) + +var AccessType_name = map[int32]string{ + 0: "UNDEFINED", + 1: "NOBODY", + 2: "ONLY_ADDRESS", + 3: "EVERYBODY", +} + +var AccessType_value = map[string]int32{ + "UNDEFINED": 0, + "NOBODY": 1, + "ONLY_ADDRESS": 2, + "EVERYBODY": 3, +} + +func (AccessType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{0} +} + +type ContractCodeHistoryOperationType int32 + +const ( + Undefined ContractCodeHistoryOperationType = 0 + ContractCodeHistoryTypeInit ContractCodeHistoryOperationType = 1 + ContractCodeHistoryTypeMigrate ContractCodeHistoryOperationType = 2 + ContractCodeHistoryTypeGenesis ContractCodeHistoryOperationType = 3 +) + +var ContractCodeHistoryOperationType_name = map[int32]string{ + 0: "Undefined", + 1: "Init", + 2: "Migrate", + 3: "Genesis", +} + +var ContractCodeHistoryOperationType_value = map[string]int32{ + "Undefined": 0, + "Init": 1, + "Migrate": 2, + "Genesis": 3, +} + +func (x ContractCodeHistoryOperationType) String() string { + return proto.EnumName(ContractCodeHistoryOperationType_name, int32(x)) +} + +func (ContractCodeHistoryOperationType) EnumDescriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{1} +} + +type AccessTypeParam struct { + Value AccessType `protobuf:"varint,1,opt,name=value,proto3,enum=wasmd.x.wasmd.v1beta1.AccessType" json:"value,omitempty" yaml:"value"` +} + +func (m *AccessTypeParam) Reset() { *m = AccessTypeParam{} } +func (m *AccessTypeParam) String() string { return proto.CompactTextString(m) } +func (*AccessTypeParam) ProtoMessage() {} +func (*AccessTypeParam) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{0} +} +func (m *AccessTypeParam) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AccessTypeParam) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AccessTypeParam.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AccessTypeParam) XXX_Merge(src proto.Message) { + xxx_messageInfo_AccessTypeParam.Merge(m, src) +} +func (m *AccessTypeParam) XXX_Size() int { + return m.Size() +} +func (m *AccessTypeParam) XXX_DiscardUnknown() { + xxx_messageInfo_AccessTypeParam.DiscardUnknown(m) +} + +var xxx_messageInfo_AccessTypeParam proto.InternalMessageInfo + +type AccessConfig struct { + Permission AccessType `protobuf:"varint,1,opt,name=permission,proto3,enum=wasmd.x.wasmd.v1beta1.AccessType" json:"permission,omitempty" yaml:"permission"` + Address github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=address,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"address,omitempty" yaml:"address"` +} + +func (m *AccessConfig) Reset() { *m = AccessConfig{} } +func (m *AccessConfig) String() string { return proto.CompactTextString(m) } +func (*AccessConfig) ProtoMessage() {} +func (*AccessConfig) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{1} +} +func (m *AccessConfig) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AccessConfig) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AccessConfig.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AccessConfig) XXX_Merge(src proto.Message) { + xxx_messageInfo_AccessConfig.Merge(m, src) +} +func (m *AccessConfig) XXX_Size() int { + return m.Size() +} +func (m *AccessConfig) XXX_DiscardUnknown() { + xxx_messageInfo_AccessConfig.DiscardUnknown(m) +} + +var xxx_messageInfo_AccessConfig proto.InternalMessageInfo + +// Params defines the set of wasm parameters. +type Params struct { + CodeUploadAccess AccessConfig `protobuf:"bytes,1,opt,name=code_upload_access,json=codeUploadAccess,proto3" json:"code_upload_access" yaml:"code_upload_access"` + InstantiateDefaultPermission AccessType `protobuf:"varint,2,opt,name=instantiate_default_permission,json=instantiateDefaultPermission,proto3,enum=wasmd.x.wasmd.v1beta1.AccessType" json:"instantiate_default_permission,omitempty" yaml:"instantiate_default_permission"` +} + +func (m *Params) Reset() { *m = Params{} } +func (*Params) ProtoMessage() {} +func (*Params) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{2} +} +func (m *Params) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Params) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Params.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Params) XXX_Merge(src proto.Message) { + xxx_messageInfo_Params.Merge(m, src) +} +func (m *Params) XXX_Size() int { + return m.Size() +} +func (m *Params) XXX_DiscardUnknown() { + xxx_messageInfo_Params.DiscardUnknown(m) +} + +var xxx_messageInfo_Params proto.InternalMessageInfo + +// CodeInfo is data for the uploaded contract WASM code +type CodeInfo struct { + CodeHash []byte `protobuf:"bytes,1,opt,name=code_hash,json=codeHash,proto3" json:"code_hash,omitempty"` + Creator github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=creator,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"creator,omitempty"` + Source string `protobuf:"bytes,3,opt,name=source,proto3" json:"source,omitempty"` + Builder string `protobuf:"bytes,4,opt,name=builder,proto3" json:"builder,omitempty"` + InstantiateConfig AccessConfig `protobuf:"bytes,5,opt,name=instantiate_config,json=instantiateConfig,proto3" json:"instantiate_config"` +} + +func (m *CodeInfo) Reset() { *m = CodeInfo{} } +func (m *CodeInfo) String() string { return proto.CompactTextString(m) } +func (*CodeInfo) ProtoMessage() {} +func (*CodeInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{3} +} +func (m *CodeInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CodeInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CodeInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_CodeInfo.Merge(m, src) +} +func (m *CodeInfo) XXX_Size() int { + return m.Size() +} +func (m *CodeInfo) XXX_DiscardUnknown() { + xxx_messageInfo_CodeInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_CodeInfo proto.InternalMessageInfo + +// ContractInfo stores a WASM contract instance +type ContractInfo struct { + CodeID uint64 `protobuf:"varint,1,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + Creator github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,2,opt,name=creator,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"creator,omitempty"` + Admin github_com_cosmos_cosmos_sdk_types.AccAddress `protobuf:"bytes,3,opt,name=admin,proto3,casttype=github.com/cosmos/cosmos-sdk/types.AccAddress" json:"admin,omitempty"` + Label string `protobuf:"bytes,4,opt,name=label,proto3" json:"label,omitempty"` + // never show this in query results, just use for sorting + // (Note: when using json tag "-" amino refused to serialize it...) + Created *AbsoluteTxPosition `protobuf:"bytes,5,opt,name=created,proto3" json:"created,omitempty"` +} + +func (m *ContractInfo) Reset() { *m = ContractInfo{} } +func (m *ContractInfo) String() string { return proto.CompactTextString(m) } +func (*ContractInfo) ProtoMessage() {} +func (*ContractInfo) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{4} +} +func (m *ContractInfo) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ContractInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ContractInfo.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ContractInfo) XXX_Merge(src proto.Message) { + xxx_messageInfo_ContractInfo.Merge(m, src) +} +func (m *ContractInfo) XXX_Size() int { + return m.Size() +} +func (m *ContractInfo) XXX_DiscardUnknown() { + xxx_messageInfo_ContractInfo.DiscardUnknown(m) +} + +var xxx_messageInfo_ContractInfo proto.InternalMessageInfo + +type ContractHistory struct { + CodeHistoryEntries []ContractCodeHistoryEntry `protobuf:"bytes,1,rep,name=code_history_entries,json=codeHistoryEntries,proto3" json:"code_history_entries"` +} + +func (m *ContractHistory) Reset() { *m = ContractHistory{} } +func (m *ContractHistory) String() string { return proto.CompactTextString(m) } +func (*ContractHistory) ProtoMessage() {} +func (*ContractHistory) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{5} +} +func (m *ContractHistory) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ContractHistory) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ContractHistory.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ContractHistory) XXX_Merge(src proto.Message) { + xxx_messageInfo_ContractHistory.Merge(m, src) +} +func (m *ContractHistory) XXX_Size() int { + return m.Size() +} +func (m *ContractHistory) XXX_DiscardUnknown() { + xxx_messageInfo_ContractHistory.DiscardUnknown(m) +} + +var xxx_messageInfo_ContractHistory proto.InternalMessageInfo + +// ContractCodeHistoryEntry stores code updates to a contract. +type ContractCodeHistoryEntry struct { + Operation ContractCodeHistoryOperationType `protobuf:"varint,1,opt,name=operation,proto3,enum=wasmd.x.wasmd.v1beta1.ContractCodeHistoryOperationType" json:"operation,omitempty"` + CodeID uint64 `protobuf:"varint,2,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty"` + Updated *AbsoluteTxPosition `protobuf:"bytes,3,opt,name=updated,proto3" json:"updated,omitempty"` + Msg encoding_json.RawMessage `protobuf:"bytes,4,opt,name=msg,proto3,casttype=encoding/json.RawMessage" json:"msg,omitempty"` +} + +func (m *ContractCodeHistoryEntry) Reset() { *m = ContractCodeHistoryEntry{} } +func (m *ContractCodeHistoryEntry) String() string { return proto.CompactTextString(m) } +func (*ContractCodeHistoryEntry) ProtoMessage() {} +func (*ContractCodeHistoryEntry) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{6} +} +func (m *ContractCodeHistoryEntry) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ContractCodeHistoryEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ContractCodeHistoryEntry.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ContractCodeHistoryEntry) XXX_Merge(src proto.Message) { + xxx_messageInfo_ContractCodeHistoryEntry.Merge(m, src) +} +func (m *ContractCodeHistoryEntry) XXX_Size() int { + return m.Size() +} +func (m *ContractCodeHistoryEntry) XXX_DiscardUnknown() { + xxx_messageInfo_ContractCodeHistoryEntry.DiscardUnknown(m) +} + +var xxx_messageInfo_ContractCodeHistoryEntry proto.InternalMessageInfo + +// AbsoluteTxPosition can be used to sort contracts +type AbsoluteTxPosition struct { + // BlockHeight is the block the contract was created at + BlockHeight int64 `protobuf:"varint,1,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` + // TxIndex is a monotonic counter within the block (actual transaction index, or gas consumed) + TxIndex uint64 `protobuf:"varint,2,opt,name=tx_index,json=txIndex,proto3" json:"tx_index,omitempty"` +} + +func (m *AbsoluteTxPosition) Reset() { *m = AbsoluteTxPosition{} } +func (m *AbsoluteTxPosition) String() string { return proto.CompactTextString(m) } +func (*AbsoluteTxPosition) ProtoMessage() {} +func (*AbsoluteTxPosition) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{7} +} +func (m *AbsoluteTxPosition) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *AbsoluteTxPosition) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_AbsoluteTxPosition.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *AbsoluteTxPosition) XXX_Merge(src proto.Message) { + xxx_messageInfo_AbsoluteTxPosition.Merge(m, src) +} +func (m *AbsoluteTxPosition) XXX_Size() int { + return m.Size() +} +func (m *AbsoluteTxPosition) XXX_DiscardUnknown() { + xxx_messageInfo_AbsoluteTxPosition.DiscardUnknown(m) +} + +var xxx_messageInfo_AbsoluteTxPosition proto.InternalMessageInfo + +// Model is a struct that holds a KV pair +type Model struct { + // hex-encode key to read it better (this is often ascii) + Key github_com_tendermint_tendermint_libs_bytes.HexBytes `protobuf:"bytes,1,opt,name=Key,proto3,casttype=github.com/tendermint/tendermint/libs/bytes.HexBytes" json:"Key,omitempty"` + // base64-encode raw value + Value []byte `protobuf:"bytes,2,opt,name=Value,proto3" json:"Value,omitempty"` +} + +func (m *Model) Reset() { *m = Model{} } +func (m *Model) String() string { return proto.CompactTextString(m) } +func (*Model) ProtoMessage() {} +func (*Model) Descriptor() ([]byte, []int) { + return fileDescriptor_45de2b3fc8aff6aa, []int{8} +} +func (m *Model) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *Model) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_Model.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *Model) XXX_Merge(src proto.Message) { + xxx_messageInfo_Model.Merge(m, src) +} +func (m *Model) XXX_Size() int { + return m.Size() +} +func (m *Model) XXX_DiscardUnknown() { + xxx_messageInfo_Model.DiscardUnknown(m) +} + +var xxx_messageInfo_Model proto.InternalMessageInfo + +func init() { + proto.RegisterEnum("wasmd.x.wasmd.v1beta1.AccessType", AccessType_name, AccessType_value) + proto.RegisterEnum("wasmd.x.wasmd.v1beta1.ContractCodeHistoryOperationType", ContractCodeHistoryOperationType_name, ContractCodeHistoryOperationType_value) + proto.RegisterType((*AccessTypeParam)(nil), "wasmd.x.wasmd.v1beta1.AccessTypeParam") + proto.RegisterType((*AccessConfig)(nil), "wasmd.x.wasmd.v1beta1.AccessConfig") + proto.RegisterType((*Params)(nil), "wasmd.x.wasmd.v1beta1.Params") + proto.RegisterType((*CodeInfo)(nil), "wasmd.x.wasmd.v1beta1.CodeInfo") + proto.RegisterType((*ContractInfo)(nil), "wasmd.x.wasmd.v1beta1.ContractInfo") + proto.RegisterType((*ContractHistory)(nil), "wasmd.x.wasmd.v1beta1.ContractHistory") + proto.RegisterType((*ContractCodeHistoryEntry)(nil), "wasmd.x.wasmd.v1beta1.ContractCodeHistoryEntry") + proto.RegisterType((*AbsoluteTxPosition)(nil), "wasmd.x.wasmd.v1beta1.AbsoluteTxPosition") + proto.RegisterType((*Model)(nil), "wasmd.x.wasmd.v1beta1.Model") +} + +func init() { proto.RegisterFile("x/wasm/internal/types/types.proto", fileDescriptor_45de2b3fc8aff6aa) } + +var fileDescriptor_45de2b3fc8aff6aa = []byte{ + // 1061 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xac, 0x56, 0xcf, 0x6f, 0x1b, 0xc5, + 0x17, 0xf7, 0xda, 0x8e, 0x9d, 0x4c, 0xfc, 0x6d, 0xdd, 0xf9, 0x26, 0xe0, 0xb8, 0xd5, 0xae, 0xb3, + 0x15, 0x28, 0x29, 0xaa, 0x4d, 0x02, 0x12, 0xa8, 0xb7, 0xf8, 0x07, 0x8d, 0x29, 0xf9, 0xa1, 0x6d, + 0x53, 0x1a, 0x24, 0x64, 0x8d, 0x77, 0x26, 0xf6, 0xd0, 0xf5, 0x8c, 0xb5, 0x33, 0x4e, 0x6d, 0x4e, + 0x1c, 0x51, 0xb8, 0x20, 0x4e, 0x70, 0x88, 0x84, 0x44, 0x0f, 0xfd, 0x07, 0xf8, 0x0f, 0x38, 0xe4, + 0x82, 0xd4, 0x23, 0x27, 0x0b, 0x92, 0xff, 0x20, 0xc7, 0x9c, 0xd0, 0xcc, 0xac, 0x6b, 0x43, 0x9b, + 0x10, 0x2a, 0x2e, 0xde, 0x9d, 0x79, 0xef, 0xf3, 0x79, 0xf3, 0x3e, 0xef, 0xbd, 0xf5, 0x80, 0xc5, + 0x7e, 0xe9, 0x09, 0x12, 0x9d, 0x12, 0x65, 0x92, 0x84, 0x0c, 0x05, 0x25, 0x39, 0xe8, 0x12, 0x61, + 0x7e, 0x8b, 0xdd, 0x90, 0x4b, 0x0e, 0xe7, 0x95, 0x03, 0x2e, 0xf6, 0x8b, 0xe6, 0xb9, 0xbf, 0xd2, + 0x24, 0x12, 0xad, 0xe4, 0xe7, 0x5a, 0xbc, 0xc5, 0xb5, 0x47, 0x49, 0xbd, 0x19, 0x67, 0xb7, 0x09, + 0xae, 0xae, 0xf9, 0x3e, 0x11, 0xe2, 0xc1, 0xa0, 0x4b, 0xb6, 0x51, 0x88, 0x3a, 0xb0, 0x0e, 0xa6, + 0xf6, 0x51, 0xd0, 0x23, 0x39, 0xab, 0x60, 0x2d, 0x5d, 0x59, 0x5d, 0x2c, 0xbe, 0x92, 0xaf, 0x38, + 0x86, 0x95, 0xb3, 0xa7, 0x43, 0x27, 0x33, 0x40, 0x9d, 0xe0, 0x8e, 0xab, 0x91, 0xae, 0x67, 0x18, + 0xee, 0x24, 0xbf, 0xff, 0xd1, 0xb1, 0xdc, 0x5f, 0x2d, 0x90, 0x31, 0xde, 0x15, 0xce, 0xf6, 0x68, + 0x0b, 0x3e, 0x02, 0xa0, 0x4b, 0xc2, 0x0e, 0x15, 0x82, 0x72, 0x76, 0xf9, 0x30, 0xf3, 0xa7, 0x43, + 0xe7, 0x9a, 0x09, 0x33, 0x86, 0xbb, 0xde, 0x04, 0x17, 0xfc, 0x1c, 0xa4, 0x11, 0xc6, 0x21, 0x11, + 0x22, 0x17, 0x2f, 0x58, 0x4b, 0x99, 0x72, 0xe5, 0x74, 0xe8, 0x5c, 0x31, 0x98, 0xc8, 0xe0, 0x9e, + 0x0d, 0x9d, 0xdb, 0x2d, 0x2a, 0xdb, 0xbd, 0x66, 0xd1, 0xe7, 0x9d, 0x92, 0xcf, 0x45, 0x87, 0x8b, + 0xe8, 0x71, 0x5b, 0xe0, 0xc7, 0x91, 0x98, 0x6b, 0xbe, 0xbf, 0x66, 0x10, 0xde, 0x88, 0x33, 0xca, + 0xe7, 0x87, 0x38, 0x48, 0x69, 0xa9, 0x04, 0x94, 0x00, 0xfa, 0x1c, 0x93, 0x46, 0xaf, 0x1b, 0x70, + 0x84, 0x1b, 0x48, 0x1f, 0x56, 0x67, 0x34, 0xbb, 0x7a, 0xf3, 0xc2, 0x8c, 0x8c, 0x14, 0xe5, 0xc5, + 0xa3, 0xa1, 0x13, 0x3b, 0x1d, 0x3a, 0x0b, 0xe6, 0x8c, 0x2f, 0x93, 0xb9, 0x5e, 0x56, 0x6d, 0xee, + 0xe8, 0x3d, 0x03, 0x85, 0xdf, 0x59, 0xc0, 0xa6, 0x4c, 0x48, 0xc4, 0x24, 0x45, 0x92, 0x34, 0x30, + 0xd9, 0x43, 0xbd, 0x40, 0x36, 0x26, 0x44, 0x8d, 0x5f, 0x56, 0xd4, 0xe5, 0xd3, 0xa1, 0xf3, 0x96, + 0x09, 0x7e, 0x31, 0xa5, 0xeb, 0xdd, 0x98, 0x70, 0xa8, 0x1a, 0xfb, 0xf6, 0x0b, 0xb3, 0xd6, 0x26, + 0xe6, 0x7e, 0x15, 0x07, 0xd3, 0x15, 0x8e, 0x49, 0x9d, 0xed, 0x71, 0x78, 0x1d, 0xcc, 0xe8, 0x84, + 0xda, 0x48, 0xb4, 0xb5, 0x28, 0x19, 0x6f, 0x5a, 0x6d, 0xac, 0x23, 0xd1, 0x86, 0xf7, 0x40, 0xda, + 0x0f, 0x09, 0x92, 0x3c, 0x8c, 0x4a, 0xb5, 0xf2, 0x1a, 0x85, 0x89, 0x18, 0xe0, 0x1b, 0x20, 0x25, + 0x78, 0x2f, 0xf4, 0x49, 0x2e, 0x51, 0xb0, 0x96, 0x66, 0xbc, 0x68, 0x05, 0x73, 0x20, 0xdd, 0xec, + 0xd1, 0x00, 0x93, 0x30, 0x97, 0xd4, 0x86, 0xd1, 0x12, 0x3e, 0x02, 0x70, 0x32, 0x5f, 0x5f, 0x97, + 0x23, 0x37, 0x75, 0xf9, 0xca, 0x25, 0x55, 0xe5, 0xbc, 0x6b, 0x13, 0x24, 0xc6, 0xe0, 0x3e, 0x8d, + 0x83, 0x4c, 0x85, 0x33, 0x19, 0x22, 0x5f, 0x6a, 0x19, 0x6e, 0x82, 0xb4, 0x96, 0x81, 0x62, 0x2d, + 0x42, 0xb2, 0x0c, 0x8e, 0x87, 0x4e, 0x4a, 0xab, 0x54, 0xf5, 0x52, 0xca, 0x54, 0xc7, 0xff, 0xad, + 0x1c, 0x77, 0xc1, 0x14, 0xc2, 0x1d, 0xca, 0xb4, 0x1a, 0xaf, 0x45, 0x65, 0xf0, 0x70, 0x0e, 0x4c, + 0x05, 0xa8, 0x49, 0x82, 0x48, 0x3d, 0xb3, 0x80, 0x95, 0xe8, 0xac, 0x04, 0x47, 0x82, 0x2d, 0x9f, + 0x27, 0x58, 0x53, 0xf0, 0xa0, 0x27, 0xc9, 0x83, 0xfe, 0x36, 0x17, 0x54, 0x52, 0xce, 0xbc, 0x11, + 0xd2, 0xfd, 0x12, 0x5c, 0x1d, 0xa9, 0xb4, 0x4e, 0x85, 0xe4, 0xe1, 0x00, 0xb6, 0xc0, 0x9c, 0xe9, + 0x17, 0xb3, 0x6e, 0x10, 0x26, 0x43, 0x4a, 0xd4, 0x3c, 0x25, 0x96, 0x66, 0x57, 0x4b, 0xe7, 0x04, + 0x19, 0xb1, 0x28, 0x41, 0x23, 0xa6, 0x1a, 0x93, 0xe1, 0x20, 0xaa, 0x90, 0x1e, 0xd0, 0x89, 0x7d, + 0x4a, 0x84, 0xfb, 0x4d, 0x1c, 0xe4, 0xce, 0x83, 0xc1, 0x1d, 0x30, 0xc3, 0xbb, 0x24, 0x44, 0x72, + 0xfc, 0x71, 0xfa, 0xe0, 0xf2, 0xa1, 0xb7, 0x46, 0x50, 0x35, 0x5d, 0xde, 0x98, 0x69, 0xb2, 0x0b, + 0xe2, 0xe7, 0x76, 0x41, 0x05, 0xa4, 0x7b, 0x5d, 0xac, 0x95, 0x4d, 0xfc, 0x6b, 0x65, 0x23, 0x24, + 0x2c, 0x82, 0x44, 0x47, 0xb4, 0x74, 0xc9, 0x32, 0xe5, 0x1b, 0x67, 0x43, 0x27, 0x47, 0x98, 0xcf, + 0x31, 0x65, 0xad, 0xd2, 0x17, 0x82, 0xb3, 0xa2, 0x87, 0x9e, 0x6c, 0x10, 0x21, 0x50, 0x8b, 0x78, + 0xca, 0xd1, 0xf5, 0x00, 0x7c, 0x99, 0x0e, 0x2e, 0x82, 0x4c, 0x33, 0xe0, 0xfe, 0xe3, 0x46, 0x9b, + 0xd0, 0x56, 0x5b, 0x6a, 0x25, 0x12, 0xde, 0xac, 0xde, 0x5b, 0xd7, 0x5b, 0x70, 0x01, 0x4c, 0xcb, + 0x7e, 0x83, 0x32, 0x4c, 0xfa, 0x26, 0x27, 0x2f, 0x2d, 0xfb, 0x75, 0xb5, 0x74, 0x29, 0x98, 0xda, + 0xe0, 0x98, 0x04, 0xf0, 0x63, 0x90, 0xb8, 0x47, 0x06, 0x66, 0xfa, 0xcb, 0x1f, 0x9e, 0x0d, 0x9d, + 0xf7, 0x27, 0x1a, 0x51, 0x12, 0x86, 0xd5, 0x17, 0x84, 0xc9, 0xc9, 0xd7, 0x80, 0x36, 0x45, 0xa9, + 0x39, 0x90, 0x44, 0x14, 0xd7, 0x49, 0xbf, 0xac, 0x5e, 0x3c, 0x45, 0xa2, 0xba, 0xf1, 0xa1, 0xfe, + 0x67, 0xd2, 0x13, 0xe2, 0x99, 0xc5, 0xad, 0x9f, 0x2d, 0x00, 0xc6, 0x1f, 0x34, 0xf8, 0x36, 0x98, + 0xd9, 0xd9, 0xac, 0xd6, 0x3e, 0xaa, 0x6f, 0xd6, 0xaa, 0xd9, 0x58, 0xfe, 0xcd, 0x83, 0xc3, 0xc2, + 0xff, 0xc7, 0xe6, 0x1d, 0x86, 0xc9, 0x1e, 0x65, 0x04, 0xc3, 0x02, 0x48, 0x6d, 0x6e, 0x95, 0xb7, + 0xaa, 0xbb, 0x59, 0x2b, 0x3f, 0x77, 0x70, 0x58, 0xc8, 0x8e, 0x9d, 0x36, 0x79, 0x93, 0xe3, 0x01, + 0x7c, 0x07, 0x64, 0xb6, 0x36, 0x3f, 0xd9, 0x6d, 0xac, 0x55, 0xab, 0x5e, 0xed, 0xfe, 0xfd, 0x6c, + 0x3c, 0xbf, 0x70, 0x70, 0x58, 0x98, 0x1f, 0xfb, 0x6d, 0xb1, 0x60, 0x10, 0x0d, 0x8c, 0x0a, 0x5b, + 0x7b, 0x58, 0xf3, 0x76, 0x35, 0x63, 0xe2, 0xef, 0x61, 0x6b, 0xfb, 0x24, 0x1c, 0x28, 0xd2, 0xfc, + 0xf4, 0xd7, 0x3f, 0xd9, 0xb1, 0x67, 0x4f, 0xed, 0xd8, 0xad, 0x5f, 0x2c, 0x50, 0xf8, 0xa7, 0x06, + 0x82, 0xff, 0x03, 0x33, 0x2f, 0x8e, 0x9c, 0x8d, 0xc1, 0x65, 0x90, 0xac, 0x33, 0x2a, 0xb3, 0x56, + 0xde, 0x39, 0x38, 0x2c, 0x5c, 0x7f, 0x05, 0x5c, 0xa1, 0x94, 0x0b, 0x2c, 0x81, 0xf4, 0x06, 0x6d, + 0x85, 0x48, 0x92, 0x6c, 0x3c, 0xef, 0x1e, 0x1c, 0x16, 0xec, 0x73, 0xbc, 0x23, 0x2f, 0x05, 0xb8, + 0x4b, 0x18, 0x11, 0x54, 0x64, 0x13, 0x17, 0x02, 0x22, 0xaf, 0x7c, 0x52, 0xa5, 0x52, 0xf6, 0x8e, + 0xfe, 0xb0, 0x63, 0xcf, 0x8e, 0x6d, 0xeb, 0xe8, 0xd8, 0xb6, 0x9e, 0x1f, 0xdb, 0xd6, 0xef, 0xc7, + 0xb6, 0xf5, 0xed, 0x89, 0x1d, 0x7b, 0x7e, 0x62, 0xc7, 0x7e, 0x3b, 0xb1, 0x63, 0x9f, 0xbd, 0x3b, + 0x51, 0xf1, 0x0a, 0x17, 0x9d, 0x4f, 0xd5, 0x05, 0x46, 0xb7, 0x73, 0xa9, 0x1f, 0x3d, 0xff, 0x7a, + 0x9d, 0x69, 0xa6, 0xf4, 0xe5, 0xe4, 0xbd, 0x3f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xba, 0x1f, 0x0b, + 0x8f, 0xee, 0x08, 0x00, 0x00, +} + +func (this *AccessTypeParam) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*AccessTypeParam) + if !ok { + that2, ok := that.(AccessTypeParam) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Value != that1.Value { + return false + } + return true +} +func (this *AccessConfig) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*AccessConfig) + if !ok { + that2, ok := that.(AccessConfig) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Permission != that1.Permission { + return false + } + if !bytes.Equal(this.Address, that1.Address) { + return false + } + return true +} +func (this *Params) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Params) + if !ok { + that2, ok := that.(Params) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !this.CodeUploadAccess.Equal(&that1.CodeUploadAccess) { + return false + } + if this.InstantiateDefaultPermission != that1.InstantiateDefaultPermission { + return false + } + return true +} +func (this *CodeInfo) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*CodeInfo) + if !ok { + that2, ok := that.(CodeInfo) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.CodeHash, that1.CodeHash) { + return false + } + if !bytes.Equal(this.Creator, that1.Creator) { + return false + } + if this.Source != that1.Source { + return false + } + if this.Builder != that1.Builder { + return false + } + if !this.InstantiateConfig.Equal(&that1.InstantiateConfig) { + return false + } + return true +} +func (this *ContractInfo) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ContractInfo) + if !ok { + that2, ok := that.(ContractInfo) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.CodeID != that1.CodeID { + return false + } + if !bytes.Equal(this.Creator, that1.Creator) { + return false + } + if !bytes.Equal(this.Admin, that1.Admin) { + return false + } + if this.Label != that1.Label { + return false + } + if !this.Created.Equal(that1.Created) { + return false + } + return true +} +func (this *ContractHistory) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ContractHistory) + if !ok { + that2, ok := that.(ContractHistory) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if len(this.CodeHistoryEntries) != len(that1.CodeHistoryEntries) { + return false + } + for i := range this.CodeHistoryEntries { + if !this.CodeHistoryEntries[i].Equal(&that1.CodeHistoryEntries[i]) { + return false + } + } + return true +} +func (this *ContractCodeHistoryEntry) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*ContractCodeHistoryEntry) + if !ok { + that2, ok := that.(ContractCodeHistoryEntry) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.Operation != that1.Operation { + return false + } + if this.CodeID != that1.CodeID { + return false + } + if !this.Updated.Equal(that1.Updated) { + return false + } + if !bytes.Equal(this.Msg, that1.Msg) { + return false + } + return true +} +func (this *AbsoluteTxPosition) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*AbsoluteTxPosition) + if !ok { + that2, ok := that.(AbsoluteTxPosition) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if this.BlockHeight != that1.BlockHeight { + return false + } + if this.TxIndex != that1.TxIndex { + return false + } + return true +} +func (this *Model) Equal(that interface{}) bool { + if that == nil { + return this == nil + } + + that1, ok := that.(*Model) + if !ok { + that2, ok := that.(Model) + if ok { + that1 = &that2 + } else { + return false + } + } + if that1 == nil { + return this == nil + } else if this == nil { + return false + } + if !bytes.Equal(this.Key, that1.Key) { + return false + } + if !bytes.Equal(this.Value, that1.Value) { + return false + } + return true +} +func (m *AccessTypeParam) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AccessTypeParam) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AccessTypeParam) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Value != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Value)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *AccessConfig) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AccessConfig) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AccessConfig) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0x12 + } + if m.Permission != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Permission)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Params) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Params) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Params) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.InstantiateDefaultPermission != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.InstantiateDefaultPermission)) + i-- + dAtA[i] = 0x10 + } + { + size, err := m.CodeUploadAccess.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *CodeInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CodeInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CodeInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size, err := m.InstantiateConfig.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + if len(m.Builder) > 0 { + i -= len(m.Builder) + copy(dAtA[i:], m.Builder) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Builder))) + i-- + dAtA[i] = 0x22 + } + if len(m.Source) > 0 { + i -= len(m.Source) + copy(dAtA[i:], m.Source) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Source))) + i-- + dAtA[i] = 0x1a + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0x12 + } + if len(m.CodeHash) > 0 { + i -= len(m.CodeHash) + copy(dAtA[i:], m.CodeHash) + i = encodeVarintTypes(dAtA, i, uint64(len(m.CodeHash))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *ContractInfo) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ContractInfo) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ContractInfo) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Created != nil { + { + size, err := m.Created.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + } + if len(m.Label) > 0 { + i -= len(m.Label) + copy(dAtA[i:], m.Label) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Label))) + i-- + dAtA[i] = 0x22 + } + if len(m.Admin) > 0 { + i -= len(m.Admin) + copy(dAtA[i:], m.Admin) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Admin))) + i-- + dAtA[i] = 0x1a + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0x12 + } + if m.CodeID != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *ContractHistory) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ContractHistory) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ContractHistory) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.CodeHistoryEntries) > 0 { + for iNdEx := len(m.CodeHistoryEntries) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.CodeHistoryEntries[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + } + } + return len(dAtA) - i, nil +} + +func (m *ContractCodeHistoryEntry) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ContractCodeHistoryEntry) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ContractCodeHistoryEntry) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Msg) > 0 { + i -= len(m.Msg) + copy(dAtA[i:], m.Msg) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Msg))) + i-- + dAtA[i] = 0x22 + } + if m.Updated != nil { + { + size, err := m.Updated.MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + if m.CodeID != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.CodeID)) + i-- + dAtA[i] = 0x10 + } + if m.Operation != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Operation)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *AbsoluteTxPosition) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *AbsoluteTxPosition) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *AbsoluteTxPosition) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.TxIndex != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.TxIndex)) + i-- + dAtA[i] = 0x10 + } + if m.BlockHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockHeight)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func (m *Model) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *Model) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *Model) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.Value) > 0 { + i -= len(m.Value) + copy(dAtA[i:], m.Value) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Value))) + i-- + dAtA[i] = 0x12 + } + if len(m.Key) > 0 { + i -= len(m.Key) + copy(dAtA[i:], m.Key) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Key))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { + offset -= sovTypes(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *AccessTypeParam) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Value != 0 { + n += 1 + sovTypes(uint64(m.Value)) + } + return n +} + +func (m *AccessConfig) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Permission != 0 { + n += 1 + sovTypes(uint64(m.Permission)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *Params) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.CodeUploadAccess.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.InstantiateDefaultPermission != 0 { + n += 1 + sovTypes(uint64(m.InstantiateDefaultPermission)) + } + return n +} + +func (m *CodeInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.CodeHash) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Source) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Builder) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = m.InstantiateConfig.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *ContractInfo) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.CodeID != 0 { + n += 1 + sovTypes(uint64(m.CodeID)) + } + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Admin) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Label) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Created != nil { + l = m.Created.Size() + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *ContractHistory) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if len(m.CodeHistoryEntries) > 0 { + for _, e := range m.CodeHistoryEntries { + l = e.Size() + n += 1 + l + sovTypes(uint64(l)) + } + } + return n +} + +func (m *ContractCodeHistoryEntry) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Operation != 0 { + n += 1 + sovTypes(uint64(m.Operation)) + } + if m.CodeID != 0 { + n += 1 + sovTypes(uint64(m.CodeID)) + } + if m.Updated != nil { + l = m.Updated.Size() + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Msg) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func (m *AbsoluteTxPosition) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.BlockHeight != 0 { + n += 1 + sovTypes(uint64(m.BlockHeight)) + } + if m.TxIndex != 0 { + n += 1 + sovTypes(uint64(m.TxIndex)) + } + return n +} + +func (m *Model) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Key) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Value) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *AccessTypeParam) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AccessTypeParam: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccessTypeParam: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + m.Value = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Value |= AccessType(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AccessConfig) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AccessConfig: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AccessConfig: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Permission", wireType) + } + m.Permission = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Permission |= AccessType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = append(m.Address[:0], dAtA[iNdEx:postIndex]...) + if m.Address == nil { + m.Address = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Params) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Params: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Params: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeUploadAccess", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.CodeUploadAccess.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field InstantiateDefaultPermission", wireType) + } + m.InstantiateDefaultPermission = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.InstantiateDefaultPermission |= AccessType(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *CodeInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CodeInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CodeInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeHash", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CodeHash = append(m.CodeHash[:0], dAtA[iNdEx:postIndex]...) + if m.CodeHash == nil { + m.CodeHash = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = append(m.Creator[:0], dAtA[iNdEx:postIndex]...) + if m.Creator == nil { + m.Creator = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Source", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Source = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Builder", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Builder = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field InstantiateConfig", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.InstantiateConfig.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ContractInfo) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ContractInfo: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ContractInfo: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = append(m.Creator[:0], dAtA[iNdEx:postIndex]...) + if m.Creator == nil { + m.Creator = []byte{} + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Admin", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Admin = append(m.Admin[:0], dAtA[iNdEx:postIndex]...) + if m.Admin == nil { + m.Admin = []byte{} + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Label", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Label = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Created", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Created == nil { + m.Created = &AbsoluteTxPosition{} + } + if err := m.Created.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ContractHistory) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ContractHistory: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ContractHistory: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeHistoryEntries", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.CodeHistoryEntries = append(m.CodeHistoryEntries, ContractCodeHistoryEntry{}) + if err := m.CodeHistoryEntries[len(m.CodeHistoryEntries)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ContractCodeHistoryEntry) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ContractCodeHistoryEntry: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ContractCodeHistoryEntry: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Operation", wireType) + } + m.Operation = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Operation |= ContractCodeHistoryOperationType(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field CodeID", wireType) + } + m.CodeID = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.CodeID |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Updated", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if m.Updated == nil { + m.Updated = &AbsoluteTxPosition{} + } + if err := m.Updated.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Msg = append(m.Msg[:0], dAtA[iNdEx:postIndex]...) + if m.Msg == nil { + m.Msg = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *AbsoluteTxPosition) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: AbsoluteTxPosition: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: AbsoluteTxPosition: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) + } + m.BlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field TxIndex", wireType) + } + m.TxIndex = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.TxIndex |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *Model) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: Model: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: Model: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Key", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Key = append(m.Key[:0], dAtA[iNdEx:postIndex]...) + if m.Key == nil { + m.Key = []byte{} + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Value", wireType) + } + var byteLen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + byteLen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if byteLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + byteLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Value = append(m.Value[:0], dAtA[iNdEx:postIndex]...) + if m.Value == nil { + m.Value = []byte{} + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if skippy < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipTypes(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowTypes + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthTypes + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupTypes + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthTypes + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthTypes = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowTypes = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupTypes = fmt.Errorf("proto: unexpected end of group") +) diff --git a/x/wasm/internal/types/types.proto b/x/wasm/internal/types/types.proto new file mode 100644 index 0000000000..6701806545 --- /dev/null +++ b/x/wasm/internal/types/types.proto @@ -0,0 +1,96 @@ +syntax = "proto3"; +package wasmd.x.wasmd.v1beta1; + +import "gogoproto/gogo.proto"; + +option go_package = "github.com/CosmWasm/wasmd/x/wasmd/internal/types"; +option (gogoproto.goproto_getters_all) = false; +option (gogoproto.equal_all) = true; + +enum AccessType { + option (gogoproto.goproto_enum_prefix) = false; + option (gogoproto.goproto_enum_stringer) = false; + UNDEFINED = 0 [(gogoproto.enumvalue_customname) = "AccessTypeUndefined"]; + NOBODY = 1 [(gogoproto.enumvalue_customname) = "AccessTypeNobody"]; + ONLY_ADDRESS = 2 [(gogoproto.enumvalue_customname) = "AccessTypeOnlyAddress"]; + EVERYBODY = 3 [(gogoproto.enumvalue_customname) = "AccessTypeEverybody"]; +} + +message AccessTypeParam { + option (gogoproto.goproto_stringer) = true; + AccessType value = 1 [(gogoproto.moretags) = "yaml:\"value\""]; +} + +message AccessConfig { + option (gogoproto.goproto_stringer) = true; + AccessType permission = 1 [(gogoproto.moretags) = "yaml:\"permission\""]; + bytes address = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress", (gogoproto.moretags) = "yaml:\"address\""]; +} + +// Params defines the set of wasm parameters. +message Params { + option (gogoproto.goproto_stringer) = false; + AccessConfig code_upload_access = 1 [(gogoproto.nullable) = false, (gogoproto.moretags) = "yaml:\"code_upload_access\""]; + AccessType instantiate_default_permission = 2 [(gogoproto.moretags) = "yaml:\"instantiate_default_permission\""]; +} + +// CodeInfo is data for the uploaded contract WASM code +message CodeInfo { + bytes code_hash = 1; + bytes creator = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + string source = 3; + string builder = 4; + AccessConfig instantiate_config = 5 [(gogoproto.nullable) = false]; +} + +// ContractInfo stores a WASM contract instance +message ContractInfo { + uint64 code_id = 1 [(gogoproto.customname) = "CodeID"]; + bytes creator = 2 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + bytes admin = 3 [(gogoproto.casttype) = "github.com/cosmos/cosmos-sdk/types.AccAddress"]; + string label = 4; + // never show this in query results, just use for sorting + // (Note: when using json tag "-" amino refused to serialize it...) + AbsoluteTxPosition created = 5; + // bytes init_msg = 5 [(gogoproto.casttype) = "encoding/json.RawMessage"]; + // + // AbsoluteTxPosition last_updated = 7; + // uint64 previous_code_id = 8 [(gogoproto.customname) = "PreviousCodeID"]; +} + +enum ContractCodeHistoryOperationType { + option (gogoproto.goproto_enum_prefix) = false; + Undefined = 0; + Init = 1 [(gogoproto.enumvalue_customname) = "ContractCodeHistoryTypeInit"]; + Migrate = 2 [(gogoproto.enumvalue_customname) = "ContractCodeHistoryTypeMigrate"]; + Genesis = 3 [(gogoproto.enumvalue_customname) = "ContractCodeHistoryTypeGenesis"]; +} + +message ContractHistory { + repeated ContractCodeHistoryEntry code_history_entries = 1 [(gogoproto.nullable) = false]; +} + +// ContractCodeHistoryEntry stores code updates to a contract. +message ContractCodeHistoryEntry { + ContractCodeHistoryOperationType operation = 1; + uint64 code_id = 2 [(gogoproto.customname) = "CodeID"]; + AbsoluteTxPosition updated = 3; + bytes msg = 4 [(gogoproto.casttype) = "encoding/json.RawMessage"]; + +} + +// AbsoluteTxPosition can be used to sort contracts +message AbsoluteTxPosition { + // BlockHeight is the block the contract was created at + int64 block_height = 1; + // TxIndex is a monotonic counter within the block (actual transaction index, or gas consumed) + uint64 tx_index = 2; +} + +// Model is a struct that holds a KV pair +message Model { + // hex-encode key to read it better (this is often ascii) + bytes Key = 1 [(gogoproto.casttype) = "github.com/tendermint/tendermint/libs/bytes.HexBytes"]; + // base64-encode raw value + bytes Value = 2; +} \ No newline at end of file diff --git a/x/wasm/module.go b/x/wasm/module.go index e7c7939fd5..91aad2c507 100644 --- a/x/wasm/module.go +++ b/x/wasm/module.go @@ -1,19 +1,24 @@ package wasm import ( + "context" "encoding/json" - - "github.com/gorilla/mux" - "github.com/spf13/cobra" - - abci "github.com/tendermint/tendermint/abci/types" + "math/rand" "github.com/CosmWasm/wasmd/x/wasm/client/cli" "github.com/CosmWasm/wasmd/x/wasm/client/rest" - "github.com/cosmos/cosmos-sdk/client/context" + "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + cdctypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/gorilla/mux" + "github.com/grpc-ecosystem/grpc-gateway/runtime" + "github.com/spf13/cobra" + abci "github.com/tendermint/tendermint/abci/types" ) var ( @@ -24,28 +29,31 @@ var ( // AppModuleBasic defines the basic application module used by the wasm module. type AppModuleBasic struct{} +func (b AppModuleBasic) RegisterLegacyAminoCodec(amino *codec.LegacyAmino) { + RegisterCodec(amino) +} + +func (b AppModuleBasic) RegisterGRPCRoutes(clientCtx client.Context, serveMux *runtime.ServeMux) { + types.RegisterQueryHandlerClient(context.Background(), serveMux, types.NewQueryClient(clientCtx)) +} + // Name returns the wasm module's name. func (AppModuleBasic) Name() string { return ModuleName } -// RegisterCodec registers the wasm module's types for the given codec. -func (AppModuleBasic) RegisterCodec(cdc *codec.Codec) { - RegisterCodec(cdc) -} - // DefaultGenesis returns default genesis state as raw bytes for the wasm // module. -func (AppModuleBasic) DefaultGenesis() json.RawMessage { - return ModuleCdc.MustMarshalJSON(&GenesisState{ +func (AppModuleBasic) DefaultGenesis(cdc codec.JSONMarshaler) json.RawMessage { + return cdc.MustMarshalJSON(&GenesisState{ Params: DefaultParams(), }) } // ValidateGenesis performs genesis state validation for the wasm module. -func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { +func (b AppModuleBasic) ValidateGenesis(marshaler codec.JSONMarshaler, config client.TxEncodingConfig, message json.RawMessage) error { var data GenesisState - err := ModuleCdc.UnmarshalJSON(bz, &data) + err := marshaler.UnmarshalJSON(message, &data) if err != nil { return err } @@ -53,18 +61,23 @@ func (AppModuleBasic) ValidateGenesis(bz json.RawMessage) error { } // RegisterRESTRoutes registers the REST routes for the wasm module. -func (AppModuleBasic) RegisterRESTRoutes(ctx context.CLIContext, rtr *mux.Router) { - rest.RegisterRoutes(ctx, rtr) +func (AppModuleBasic) RegisterRESTRoutes(cliCtx client.Context, rtr *mux.Router) { + rest.RegisterRoutes(cliCtx, rtr) } // GetTxCmd returns the root tx command for the wasm module. -func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetTxCmd(cdc) +func (b AppModuleBasic) GetTxCmd() *cobra.Command { + return cli.GetTxCmd() } // GetQueryCmd returns no root query command for the wasm module. -func (AppModuleBasic) GetQueryCmd(cdc *codec.Codec) *cobra.Command { - return cli.GetQueryCmd(cdc) +func (b AppModuleBasic) GetQueryCmd() *cobra.Command { + return cli.GetQueryCmd() +} + +// RegisterInterfaceTypes implements InterfaceModule +func (b AppModuleBasic) RegisterInterfaces(registry cdctypes.InterfaceRegistry) { + types.RegisterInterfaces(registry) } //____________________________________________________________________________ @@ -83,22 +96,20 @@ func NewAppModule(keeper Keeper) AppModule { } } -// Name returns the wasm module's name. -func (AppModule) Name() string { - return ModuleName +func (am AppModule) RegisterServices(configurator module.Configurator) { + types.RegisterQueryServer(configurator.QueryServer(), NewQuerier(am.keeper)) +} + +func (am AppModule) LegacyQuerierHandler(amino *codec.LegacyAmino) sdk.Querier { + return keeper.NewLegacyQuerier(am.keeper) } // RegisterInvariants registers the wasm module invariants. func (am AppModule) RegisterInvariants(ir sdk.InvariantRegistry) {} // Route returns the message routing key for the wasm module. -func (AppModule) Route() string { - return RouterKey -} - -// NewHandler returns an sdk.Handler for the wasm module. -func (am AppModule) NewHandler() sdk.Handler { - return NewHandler(am.keeper) +func (am AppModule) Route() sdk.Route { + return sdk.NewRoute(RouterKey, NewHandler(am.keeper)) } // QuerierRoute returns the wasm module's querier route name. @@ -106,16 +117,11 @@ func (AppModule) QuerierRoute() string { return QuerierRoute } -// NewQuerierHandler returns the wasm module sdk.Querier. -func (am AppModule) NewQuerierHandler() sdk.Querier { - return NewQuerier(am.keeper) -} - // InitGenesis performs genesis initialization for the wasm module. It returns // no validator updates. -func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.ValidatorUpdate { +func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONMarshaler, data json.RawMessage) []abci.ValidatorUpdate { var genesisState GenesisState - ModuleCdc.MustUnmarshalJSON(data, &genesisState) + cdc.MustUnmarshalJSON(data, &genesisState) if err := InitGenesis(ctx, am.keeper, genesisState); err != nil { panic(err) } @@ -124,9 +130,9 @@ func (am AppModule) InitGenesis(ctx sdk.Context, data json.RawMessage) []abci.Va // ExportGenesis returns the exported genesis state as raw bytes for the wasm // module. -func (am AppModule) ExportGenesis(ctx sdk.Context) json.RawMessage { +func (am AppModule) ExportGenesis(ctx sdk.Context, cdc codec.JSONMarshaler) json.RawMessage { gs := ExportGenesis(ctx, am.keeper) - return ModuleCdc.MustMarshalJSON(gs) + return cdc.MustMarshalJSON(gs) } // BeginBlock returns the begin blocker for the wasm module. @@ -137,3 +143,30 @@ func (am AppModule) BeginBlock(_ sdk.Context, _ abci.RequestBeginBlock) {} func (AppModule) EndBlock(_ sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate { return []abci.ValidatorUpdate{} } + +//____________________________________________________________________________ + +// AppModuleSimulation functions + +// GenerateGenesisState creates a randomized GenState of the bank module. +func (AppModule) GenerateGenesisState(simState *module.SimulationState) { +} + +// ProposalContents doesn't return any content functions for governance proposals. +func (AppModule) ProposalContents(simState module.SimulationState) []simtypes.WeightedProposalContent { + return nil +} + +// RandomizedParams creates randomized bank param changes for the simulator. +func (AppModule) RandomizedParams(r *rand.Rand) []simtypes.ParamChange { + return nil +} + +// RegisterStoreDecoder registers a decoder for supply module's types +func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { +} + +// WeightedOperations returns the all the gov module operations with their respective weights. +func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { + return nil +} diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go index 7c0a91c16e..afff454bd6 100644 --- a/x/wasm/module_test.go +++ b/x/wasm/module_test.go @@ -4,46 +4,42 @@ import ( "encoding/json" "fmt" "io/ioutil" - "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" - "github.com/cosmos/cosmos-sdk/x/auth" + authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" + bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" + "github.com/dvsekhvalnov/jose2go/base64url" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/crypto" "github.com/tendermint/tendermint/crypto/ed25519" - "github.com/tendermint/tendermint/libs/kv" - - "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" ) type testData struct { module module.AppModule ctx sdk.Context - acctKeeper auth.AccountKeeper + acctKeeper authkeeper.AccountKeeper keeper Keeper + bankKeeper bankkeeper.Keeper } // returns a cleanup function, which must be defered on -func setupTest(t *testing.T) (testData, func()) { - tempDir, err := ioutil.TempDir("", "wasm") - require.NoError(t, err) - - ctx, keepers := CreateTestInput(t, false, tempDir, "staking", nil, nil) - acctKeeper, keeper := keepers.AccountKeeper, keepers.WasmKeeper +func setupTest(t *testing.T) testData { + ctx, keepers := CreateTestInput(t, false, "staking", nil, nil) + acctKeeper, keeper, bankKeeper := keepers.AccountKeeper, keepers.WasmKeeper, keepers.BankKeeper data := testData{ module: NewAppModule(keeper), ctx: ctx, acctKeeper: acctKeeper, keeper: keeper, + bankKeeper: bankKeeper, } - cleanup := func() { os.RemoveAll(tempDir) } - return data, cleanup + return data } func keyPubAddr() (crypto.PrivKey, crypto.PubKey, sdk.AccAddress) { @@ -74,32 +70,32 @@ func TestHandleCreate(t *testing.T) { isValid bool }{ "empty": { - msg: MsgStoreCode{}, + msg: &MsgStoreCode{}, isValid: false, }, "invalid wasm": { - msg: MsgStoreCode{ + msg: &MsgStoreCode{ Sender: addr1, WASMByteCode: []byte("foobar"), }, isValid: false, }, "valid wasm": { - msg: MsgStoreCode{ + msg: &MsgStoreCode{ Sender: addr1, WASMByteCode: testContract, }, isValid: true, }, "other valid wasm": { - msg: MsgStoreCode{ + msg: &MsgStoreCode{ Sender: addr1, WASMByteCode: maskContract, }, isValid: true, }, "old wasm (0.7)": { - msg: MsgStoreCode{ + msg: &MsgStoreCode{ Sender: addr1, WASMByteCode: oldContract, }, @@ -110,11 +106,10 @@ func TestHandleCreate(t *testing.T) { for name, tc := range cases { tc := tc t.Run(name, func(t *testing.T) { - data, cleanup := setupTest(t) - defer cleanup() + data := setupTest(t) - h := data.module.NewHandler() - q := data.module.NewQuerierHandler() + h := data.module.Route().Handler() + q := data.module.LegacyQuerierHandler(nil) res, err := h(data.ctx, tc.msg) if !tc.isValid { @@ -141,16 +136,15 @@ type state struct { } func TestHandleInstantiate(t *testing.T) { - data, cleanup := setupTest(t) - defer cleanup() + data := setupTest(t) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) - creator := createFakeFundedAccount(data.ctx, data.acctKeeper, deposit) + creator := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, deposit) - h := data.module.NewHandler() - q := data.module.NewQuerierHandler() + h := data.module.Route().Handler() + q := data.module.LegacyQuerierHandler(nil) - msg := MsgStoreCode{ + msg := &MsgStoreCode{ Sender: creator, WASMByteCode: testContract, } @@ -175,7 +169,7 @@ func TestHandleInstantiate(t *testing.T) { InitMsg: initMsgBz, InitFunds: nil, } - res, err = h(data.ctx, initCmd) + res, err = h(data.ctx, &initCmd) require.NoError(t, err) contractAddr := sdk.AccAddress(res.Data) require.Equal(t, "cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5", contractAddr.String()) @@ -199,18 +193,17 @@ func TestHandleInstantiate(t *testing.T) { } func TestHandleExecute(t *testing.T) { - data, cleanup := setupTest(t) - defer cleanup() + data := setupTest(t) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(data.ctx, data.acctKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(data.ctx, data.acctKeeper, topUp) + creator := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, topUp) - h := data.module.NewHandler() - q := data.module.NewQuerierHandler() + h := data.module.Route().Handler() + q := data.module.LegacyQuerierHandler(nil) - msg := MsgStoreCode{ + msg := &MsgStoreCode{ Sender: creator, WASMByteCode: testContract, } @@ -232,7 +225,7 @@ func TestHandleExecute(t *testing.T) { InitMsg: initMsgBz, InitFunds: deposit, } - res, err = h(data.ctx, initCmd) + res, err = h(data.ctx, &initCmd) require.NoError(t, err) contractAddr := sdk.AccAddress(res.Data) require.Equal(t, "cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5", contractAddr.String()) @@ -252,12 +245,12 @@ func TestHandleExecute(t *testing.T) { creatorAcct := data.acctKeeper.GetAccount(data.ctx, creator) require.NotNil(t, creatorAcct) // we started at 2*deposit, should have spent one above - assert.Equal(t, deposit, creatorAcct.GetCoins()) + assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, creatorAcct.GetAddress())) // ensure contract has updated balance contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) - assert.Equal(t, deposit, contractAcct.GetCoins()) + assert.Equal(t, deposit, data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) execCmd := MsgExecuteContract{ Sender: fred, @@ -265,11 +258,13 @@ func TestHandleExecute(t *testing.T) { Msg: []byte(`{"release":{}}`), SentFunds: topUp, } - res, err = h(data.ctx, execCmd) + res, err = h(data.ctx, &execCmd) require.NoError(t, err) // this should be standard x/wasm init event, plus 2 bank send event, plus a special event from the contract require.Equal(t, 4, len(res.Events), prettyEvents(res.Events)) - assert.Equal(t, "transfer", res.Events[0].Type) + + require.Equal(t, "transfer", res.Events[0].Type) + require.Len(t, res.Events[0].Attributes, 3) assertAttribute(t, "recipient", contractAddr.String(), res.Events[0].Attributes[0]) assertAttribute(t, "sender", fred.String(), res.Events[0].Attributes[1]) assertAttribute(t, "amount", "5000denom", res.Events[0].Attributes[2]) @@ -289,13 +284,13 @@ func TestHandleExecute(t *testing.T) { // ensure bob now exists and got both payments released bobAcct = data.acctKeeper.GetAccount(data.ctx, bob) require.NotNil(t, bobAcct) - balance := bobAcct.GetCoins() + balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) assert.Equal(t, deposit.Add(topUp...), balance) // ensure contract has updated balance contractAcct = data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins(nil), contractAcct.GetCoins()) + assert.Equal(t, sdk.Coins(nil), data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) // ensure all contract state is as after init assertCodeList(t, q, data.ctx, 1) @@ -311,17 +306,16 @@ func TestHandleExecute(t *testing.T) { } func TestHandleExecuteEscrow(t *testing.T) { - data, cleanup := setupTest(t) - defer cleanup() + data := setupTest(t) deposit := sdk.NewCoins(sdk.NewInt64Coin("denom", 100000)) topUp := sdk.NewCoins(sdk.NewInt64Coin("denom", 5000)) - creator := createFakeFundedAccount(data.ctx, data.acctKeeper, deposit.Add(deposit...)) - fred := createFakeFundedAccount(data.ctx, data.acctKeeper, topUp) + creator := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, deposit.Add(deposit...)) + fred := createFakeFundedAccount(t, data.ctx, data.acctKeeper, data.bankKeeper, topUp) - h := data.module.NewHandler() + h := data.module.Route().Handler() - msg := MsgStoreCode{ + msg := &MsgStoreCode{ Sender: creator, WASMByteCode: testContract, } @@ -343,7 +337,7 @@ func TestHandleExecuteEscrow(t *testing.T) { InitMsg: initMsgBz, InitFunds: deposit, } - res, err = h(data.ctx, initCmd) + res, err = h(data.ctx, &initCmd) require.NoError(t, err) contractAddr := sdk.AccAddress(res.Data) require.Equal(t, "cosmos18vd8fpwxzck93qlwghaj6arh4p7c5n89uzcee5", contractAddr.String()) @@ -360,19 +354,19 @@ func TestHandleExecuteEscrow(t *testing.T) { Msg: handleMsgBz, SentFunds: topUp, } - res, err = h(data.ctx, execCmd) + res, err = h(data.ctx, &execCmd) require.NoError(t, err) // ensure bob now exists and got both payments released bobAcct := data.acctKeeper.GetAccount(data.ctx, bob) require.NotNil(t, bobAcct) - balance := bobAcct.GetCoins() + balance := data.bankKeeper.GetAllBalances(data.ctx, bobAcct.GetAddress()) assert.Equal(t, deposit.Add(topUp...), balance) // ensure contract has updated balance contractAcct := data.acctKeeper.GetAccount(data.ctx, contractAddr) require.NotNil(t, contractAcct) - assert.Equal(t, sdk.Coins(nil), contractAcct.GetCoins()) + assert.Equal(t, sdk.Coins(nil), data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) } type prettyEvent struct { @@ -380,7 +374,7 @@ type prettyEvent struct { Attr []sdk.Attribute } -func prettyEvents(evts sdk.Events) string { +func prettyEvents(evts []abci.Event) string { res := make([]prettyEvent, len(evts)) for i, e := range evts { res[i] = prettyEvent{ @@ -395,7 +389,7 @@ func prettyEvents(evts sdk.Events) string { return string(bz) } -func prettyAttrs(attrs []kv.Pair) []sdk.Attribute { +func prettyAttrs(attrs []abci.EventAttribute) []sdk.Attribute { pretty := make([]sdk.Attribute, len(attrs)) for i, a := range attrs { pretty[i] = prettyAttr(a) @@ -403,11 +397,12 @@ func prettyAttrs(attrs []kv.Pair) []sdk.Attribute { return pretty } -func prettyAttr(attr kv.Pair) sdk.Attribute { +func prettyAttr(attr abci.EventAttribute) sdk.Attribute { return sdk.NewAttribute(string(attr.Key), string(attr.Value)) } -func assertAttribute(t *testing.T, key string, value string, attr kv.Pair) { +func assertAttribute(t *testing.T, key string, value string, attr abci.EventAttribute) { + t.Helper() assert.Equal(t, key, string(attr.Key), prettyAttr(attr)) assert.Equal(t, value, string(attr.Value), prettyAttr(attr)) } @@ -433,17 +428,19 @@ func assertCodeBytes(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uint64 bz, sdkerr := q(ctx, path, abci.RequestQuery{}) require.NoError(t, sdkerr) - if len(bz) == 0 { - require.Equal(t, len(expectedBytes), 0) + if len(expectedBytes) == 0 { + require.Equal(t, len(bz), 0, "%q", string(bz)) return } - - var res GetCodeResponse + var res map[string]interface{} err := json.Unmarshal(bz, &res) require.NoError(t, err) - assert.Equal(t, expectedBytes, res.Data) - assert.Equal(t, codeID, res.ID) + require.Contains(t, res, "data") + b, err := base64url.Decode(res["data"].(string)) + require.NoError(t, err) + assert.Equal(t, expectedBytes, b) + assert.EqualValues(t, codeID, res["id"]) } func assertContractList(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uint64, addrs []string) { @@ -468,6 +465,7 @@ func assertContractList(t *testing.T, q sdk.Querier, ctx sdk.Context, codeID uin } func assertContractState(t *testing.T, q sdk.Querier, ctx sdk.Context, addr sdk.AccAddress, expected state) { + t.Helper() path := []string{QueryGetContractState, addr.String(), keeper.QueryMethodContractStateAll} bz, sdkerr := q(ctx, path, abci.RequestQuery{}) require.NoError(t, sdkerr) @@ -484,6 +482,7 @@ func assertContractState(t *testing.T, q sdk.Querier, ctx sdk.Context, addr sdk. } func assertContractInfo(t *testing.T, q sdk.Querier, ctx sdk.Context, addr sdk.AccAddress, codeID uint64, creator sdk.AccAddress) { + t.Helper() path := []string{QueryGetContract, addr.String()} bz, sdkerr := q(ctx, path, abci.RequestQuery{}) require.NoError(t, sdkerr) @@ -496,11 +495,11 @@ func assertContractInfo(t *testing.T, q sdk.Querier, ctx sdk.Context, addr sdk.A assert.Equal(t, creator, res.Creator) } -func createFakeFundedAccount(ctx sdk.Context, am auth.AccountKeeper, coins sdk.Coins) sdk.AccAddress { +func createFakeFundedAccount(t *testing.T, ctx sdk.Context, am authkeeper.AccountKeeper, bankKeeper bankkeeper.Keeper, coins sdk.Coins) sdk.AccAddress { + t.Helper() _, _, addr := keyPubAddr() - baseAcct := auth.NewBaseAccountWithAddress(addr) - _ = baseAcct.SetCoins(coins) - am.SetAccount(ctx, &baseAcct) - + acc := am.NewAccountWithAddress(ctx, addr) + am.SetAccount(ctx, acc) + require.NoError(t, bankKeeper.SetBalances(ctx, addr, coins)) return addr }