diff --git a/.circleci/config.yml b/.circleci/config.yml index 7156f72f72..120ef3f2af 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -3,7 +3,7 @@ version: 2.1 executors: golang: docker: - - image: circleci/golang:1.14 + - image: circleci/golang:1.15 working_directory: /go/src/github.com/cosmwasm/wasmd commands: @@ -71,6 +71,7 @@ jobs: - run: name: Run tests with coverage command: | + export GORACE=halt_on_error=1 export VERSION="$(git describe --tags --long | sed 's/v\(.*\)/\1/')" export GO111MODULE=on mkdir -p /tmp/logs /tmp/workspace/profiles diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e0754873b..9c38f88933 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -44,7 +44,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * (wasmd) [\#163](https://github.com/CosmWasm/wasmd/issues/163) Control who can instantiate code * (wasmd) [\#164](https://github.com/CosmWasm/wasmd/issues/164) Control who can upload code * (wasmd) [\#173](https://github.com/CosmWasm/wasmd/issues/173) Gov proposal types and handler -* (wasmd) [\#122](https://github.com/CosmWasm/wasmd/pull/122]) Migrate contract backend functionality with go-cosmwasm stub impl +* (wasmd) [\#122](https://github.com/CosmWasm/wasmd/pull/122]) Migrate contract backend functionality with wasmvm stub impl * (wasmd)[\#2](https://github.com/cosmwasm/wasmd/pull/22) Improve wasm contract queries (all, raw, smart) * (wasmd) [\#119](https://github.com/cosmwasm/wasmd/pull/119) Add support for the `--inter-block-cache` CLI flag and configuration. diff --git a/Dockerfile b/Dockerfile index ec03669702..8b2daa13f4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ # docker build . -t cosmwasm/wasmd:latest # docker run --rm -it cosmwasm/wasmd:latest /bin/sh -FROM cosmwasm/go-ext-builder:0.8.2-alpine AS rust-builder +FROM cosmwasm/go-ext-builder:0002-alpine AS rust-builder RUN apk add git @@ -9,17 +9,16 @@ WORKDIR /code COPY go.* /code/ # download all deps -RUN go mod download github.com/CosmWasm/go-cosmwasm +RUN go mod download github.com/CosmWasm/wasmvm -# build go-cosmwasm *.a and install it -RUN export GO_WASM_DIR=$(go list -f "{{ .Dir }}" -m github.com/CosmWasm/go-cosmwasm) && \ +# build wasmvm *.a and install it +RUN export GO_WASM_DIR=$(go list -f "{{ .Dir }}" -m github.com/CosmWasm/wasmvm) && \ cd ${GO_WASM_DIR} && \ cargo build --release --features backtraces --example muslc && \ - mv ${GO_WASM_DIR}/target/release/examples/libmuslc.a /lib/libgo_cosmwasm_muslc.a - + mv ${GO_WASM_DIR}/target/release/examples/libmuslc.a /lib/libwasmvm_muslc.a # -------------------------------------------------------- -FROM cosmwasm/go-ext-builder:0.8.2-alpine AS go-builder +FROM cosmwasm/go-ext-builder:0002-alpine AS go-builder RUN apk add git # NOTE: add these to run with LEDGER_ENABLED=true @@ -28,7 +27,7 @@ RUN apk add git WORKDIR /code COPY . /code/ -COPY --from=rust-builder /lib/libgo_cosmwasm_muslc.a /lib/libgo_cosmwasm_muslc.a +COPY --from=rust-builder /lib/libwasmvm_muslc.a /lib/libwasmvm_muslc.a # force it to use static lib (from above) not standard libgo_cosmwasm.so file RUN LEDGER_ENABLED=false BUILD_TAGS=muslc make build diff --git a/Dockerfile.old b/Dockerfile.old deleted file mode 100644 index 75b779492f..0000000000 --- a/Dockerfile.old +++ /dev/null @@ -1,39 +0,0 @@ -# Simple usage with a mounted data directory: -# > docker build -t gaia . -# > docker run -it -p 46657:46657 -p 46656:46656 -v ~/.wasmd:/root/.wasmd -v ~/.wasmcli:/root/.wasmcli gaia wasmd init -# > docker run -it -p 46657:46657 -p 46656:46656 -v ~/.wasmd:/root/.wasmd -v ~/.wasmcli:/root/.wasmcli gaia wasmd start -FROM golang:1.13-buster AS build-env - -# Install minimum necessary dependencies, build Cosmos SDK, remove packages -RUN apt update -RUN apt install -y curl git build-essential -# debug: for live editting in the image -RUN apt install -y vim - -# Set working directory for the build -WORKDIR /go/src/github.com/cosmwasm/wasmd - -# Add source files -COPY . . -# -RUN make tools -RUN make install - -# Install libgo_cosmwasm.so to a shared directory where it is readable by all users -# See https://github.com/CosmWasm/wasmd/issues/43#issuecomment-608366314 -# Note that CosmWasm gets turned into !cosm!wasm in the pkg/mod cache -RUN cp /go/pkg/mod/github.com/\!cosm\!wasm/go-cosmwasm@v*/api/libgo_cosmwasm.so /lib/x86_64-linux-gnu - -COPY docker/* /opt/ -RUN chmod +x /opt/*.sh - -WORKDIR /opt - -# rest server -EXPOSE 1317 -# tendermint p2p -EXPOSE 26656 -# tendermint rpc -EXPOSE 26657 - -CMD ["wasmd"] diff --git a/INTEGRATION.md b/INTEGRATION.md index 0a4710f389..207f38613e 100644 --- a/INTEGRATION.md +++ b/INTEGRATION.md @@ -19,14 +19,14 @@ hardware it runs on. We currently only support Intel/AMD64 CPUs and OSX or Linux. For Linux, the standard build commands work for `glibc` systems (Ubuntu, Debian, CentOS, etc). If you wish to compile -for a `muslc` based system (like alpine), you need to compile a static library go-cosmwasm locally +for a `muslc` based system (like alpine), you need to compile a static library wasmvm locally and compile go with the `muslc` build tag. Or just use the [Dockerfile](./Dockerfile), which builds a static go binary in an alpine system. This limit comes from the Rust dll we use to run the wasm code, which comes -from [`go-cosmwasm`](https://github.com/CosmWasm/go-cosmwasm). There are open issues -for adding [ARM support](https://github.com/CosmWasm/go-cosmwasm/issues/53), and -adding [Windows support](https://github.com/CosmWasm/go-cosmwasm/issues/28). +from [`wasmvm`](https://github.com/CosmWasm/wasmvm). There are open issues +for adding [ARM support](https://github.com/CosmWasm/wasmvm/issues/53), and +adding [Windows support](https://github.com/CosmWasm/wasmvm/issues/28). However, these issues are not high on the roadmap and unless you are championing them, please count on the current limits for the near future. diff --git a/README.md b/README.md index 268dbd928e..eed4372c88 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ addition of the `x/wasm` module. ## Supported Systems -The supported systems are limited by the dlls created in [`go-cosmwasm`](https://github.com/CosmWasm/go-cosmwasm). In particular, **we only support MacOS and Linux**. +The supported systems are limited by the dlls created in [`wasmvm`](https://github.com/CosmWasm/wasmvm). In particular, **we only support MacOS and Linux**. For linux, the default is to build for glibc, and we cross-compile with CentOS 7 to provide backwards compatibility for `glibc 2.12+`. This includes all known supported distributions using glibc (CentOS 7 uses 2.12, obsolete Debian Jessy uses 2.19). diff --git a/app/app.go b/app/app.go index 61f351df46..3072d5110d 100644 --- a/app/app.go +++ b/app/app.go @@ -10,7 +10,6 @@ import ( "github.com/gorilla/mux" "github.com/rakyll/statik/fs" "github.com/spf13/cast" - "github.com/spf13/viper" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" "github.com/tendermint/tendermint/libs/log" @@ -240,12 +239,6 @@ type WasmApp struct { sm *module.SimulationManager } -// WasmWrapper allows us to use namespacing in the config file -// This is only used for parsing in the app, x/wasm expects WasmConfig -type WasmWrapper struct { - Wasm wasm.Config `mapstructure:"wasm"` -} - // NewWasmApp returns a reference to an initialized WasmApp. func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest bool, skipUpgradeHeights map[int64]bool, homePath string, invCheckPeriod uint, enabledProposals []wasm.ProposalType, @@ -358,13 +351,10 @@ func NewWasmApp(logger log.Logger, db dbm.DB, traceStore io.Writer, loadLatest b var wasmRouter = bApp.Router() wasmDir := filepath.Join(homePath, "wasm") - wasmWrap := WasmWrapper{Wasm: wasm.DefaultWasmConfig()} - err := viper.Unmarshal(&wasmWrap) + wasmConfig, err := wasm.ReadWasmConfig(appOpts) if err != nil { panic("error while reading wasm config: " + err.Error()) } - wasmConfig := wasmWrap.Wasm - // The last arguments can contain custom message handlers, and custom query handlers, // if we want to allow any custom callbacks supportedFeatures := "staking" diff --git a/cmd/wasmd/root.go b/cmd/wasmd/root.go index e5d290f083..541b47e6cc 100644 --- a/cmd/wasmd/root.go +++ b/cmd/wasmd/root.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" + "github.com/CosmWasm/wasmd/x/wasm" "github.com/spf13/cast" "github.com/spf13/cobra" tmcli "github.com/tendermint/tendermint/libs/cli" @@ -115,6 +116,7 @@ func initRootCmd(rootCmd *cobra.Command, encodingConfig app.EncodingConfig) { func addModuleInitFlags(startCmd *cobra.Command) { crisis.AddModuleInitFlags(startCmd) + wasm.AddModuleInitFlags(startCmd) } func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application { diff --git a/contrib/local/02-contracts.sh b/contrib/local/02-contracts.sh index b0322eb381..0f37cab486 100755 --- a/contrib/local/02-contracts.sh +++ b/contrib/local/02-contracts.sh @@ -33,7 +33,7 @@ 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") +KEY=$(echo "$RESP" | jq -r ".[0].key") wasmcli query wasm contract-state raw "$CONTRACT" "$KEY" -o json diff --git a/go.mod b/go.mod index 5e9592a681..e36b452126 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/CosmWasm/wasmd go 1.15 require ( - github.com/CosmWasm/go-cosmwasm v0.11.0 + github.com/CosmWasm/wasmvm v0.12.0-alpha1 github.com/cosmos/cosmos-sdk v0.40.0-rc3 github.com/cosmos/iavl v0.15.0-rc4 github.com/dvsekhvalnov/jose2go v0.0.0-20200901110807-248326c1351b diff --git a/go.sum b/go.sum index 8d58573838..83eb915fec 100644 --- a/go.sum +++ b/go.sum @@ -18,8 +18,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03 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.11.0 h1:H+7Xzh2tEquJXuP4q1VN7ekdheAQvCjD4FRmlPqcXnQ= -github.com/CosmWasm/go-cosmwasm v0.11.0/go.mod h1:gAFCwllx97ejI+m9SqJQrmd2SBW7HA0fOjvWWJjM2uc= +github.com/CosmWasm/wasmvm v0.12.0-alpha1 h1:UPaemjM+O/9uQRDCiExXPpcUlMJ5Zo8N/BUvqjheb5A= +github.com/CosmWasm/wasmvm v0.12.0-alpha1/go.mod h1:tbXGE9Jz6sYpiJroGr71OQ5TFOufq/P5LWsruA2u6JE= 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= diff --git a/x/wasm/IBC.md b/x/wasm/IBC.md index a7a99948f6..d5f1b8144b 100644 --- a/x/wasm/IBC.md +++ b/x/wasm/IBC.md @@ -183,7 +183,7 @@ Packet callbacks: ```go package packets -// for reference: this is more like what we pass to go-cosmwasm +// for reference: this is more like what we pass to wasmvm // 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: diff --git a/x/wasm/README.md b/x/wasm/README.md index eedea71be2..302653fcfc 100644 --- a/x/wasm/README.md +++ b/x/wasm/README.md @@ -4,15 +4,21 @@ This should be a brief overview of the functionality ## Configuration -You can add the following section to `config/app.toml`. Below is shown with defaults: +You can add the following section to `config/app.toml`: ```toml [wasm] # This is the maximum sdk gas (wasm and storage) that we allow for any x/wasm "smart" queries query_gas_limit = 300000 -# This is the number of wasm vm instances we keep cached in memory for speed-up -# Warning: this is currently unstable and may lead to crashes, best to keep for 0 unless testing locally -lru_size = 0 +# This defines the memory size for Wasm modules that we can keep cached to speed-up instantiation +# The value is in MiB not bytes +memory_cache_size = 300 +``` + +The values can also be set via CLI flags on with the `start` command: +```shell script +--wasm.memory_cache_size uint32 Sets the size in MiB (NOT bytes) of an in-memory cache for wasm modules. Set to 0 to disable. (default 100) +--wasm.query_gas_limit uint Set the max gas that can be spent on executing a query with a Wasm contract (default 3000000) ``` ## Events diff --git a/x/wasm/genesis_test.go b/x/wasm/genesis_test.go index d14ac52ea4..9db40894b5 100644 --- a/x/wasm/genesis_test.go +++ b/x/wasm/genesis_test.go @@ -8,9 +8,6 @@ import ( "github.com/stretchr/testify/require" ) -type contractState struct { -} - func TestInitGenesis(t *testing.T) { data := setupTest(t) @@ -22,56 +19,13 @@ func TestInitGenesis(t *testing.T) { h := data.module.Route().Handler() q := data.module.LegacyQuerierHandler(nil) - t.Log("fail with invalid source url") msg := MsgStoreCode{ - Sender: creator, - WASMByteCode: testContract, - Source: "someinvalidurl", - Builder: "", - } - - err := msg.ValidateBasic() - require.Error(t, err) - - _, err = h(data.ctx, &msg) - require.Error(t, err) - - t.Log("fail with relative source url") - msg = MsgStoreCode{ - Sender: creator, - WASMByteCode: testContract, - Source: "./testdata/escrow.wasm", - Builder: "", - } - - err = msg.ValidateBasic() - require.Error(t, err) - - _, err = h(data.ctx, &msg) - require.Error(t, err) - - t.Log("fail with invalid build tag") - msg = MsgStoreCode{ - Sender: creator, - WASMByteCode: testContract, - Source: "", - Builder: "somerandombuildtag-0.6.2", - } - - err = msg.ValidateBasic() - require.Error(t, err) - - _, err = h(data.ctx, &msg) - require.Error(t, err) - - t.Log("no error with valid source and build tag") - msg = MsgStoreCode{ Sender: creator, WASMByteCode: testContract, Source: "https://github.com/CosmWasm/wasmd/blob/master/x/wasm/testdata/escrow.wasm", Builder: "confio/cosmwasm-opt:0.7.0", } - err = msg.ValidateBasic() + err := msg.ValidateBasic() require.NoError(t, err) res, err := h(data.ctx, &msg) diff --git a/x/wasm/internal/keeper/api.go b/x/wasm/internal/keeper/api.go index 2eec6945ef..01c817337d 100644 --- a/x/wasm/internal/keeper/api.go +++ b/x/wasm/internal/keeper/api.go @@ -2,7 +2,7 @@ package keeper import ( "fmt" - cosmwasm "github.com/CosmWasm/go-cosmwasm" + wasmvm "github.com/CosmWasm/wasmvm" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -23,7 +23,7 @@ func canonicalAddress(human string) ([]byte, uint64, error) { return bz, CostCanonical, err } -var cosmwasmAPI = cosmwasm.GoAPI{ +var cosmwasmAPI = wasmvm.GoAPI{ HumanAddress: humanAddress, CanonicalAddress: canonicalAddress, } diff --git a/x/wasm/internal/keeper/handler_plugin.go b/x/wasm/internal/keeper/handler_plugin.go index f9ad03022f..dcfbc0fb96 100644 --- a/x/wasm/internal/keeper/handler_plugin.go +++ b/x/wasm/internal/keeper/handler_plugin.go @@ -4,8 +4,8 @@ import ( "encoding/json" "fmt" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" @@ -26,10 +26,10 @@ func NewMessageHandler(router sdk.Router, customEncoders *MessageEncoders) Messa } } -type BankEncoder func(sender sdk.AccAddress, msg *wasmTypes.BankMsg) ([]sdk.Msg, error) +type BankEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) type CustomEncoder func(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) -type StakingEncoder func(sender sdk.AccAddress, msg *wasmTypes.StakingMsg) ([]sdk.Msg, error) -type WasmEncoder func(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, error) +type StakingEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) +type WasmEncoder func(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) type MessageEncoders struct { Bank BankEncoder @@ -66,7 +66,7 @@ func (e MessageEncoders) Merge(o *MessageEncoders) MessageEncoders { return e } -func (e MessageEncoders) Encode(contractAddr sdk.AccAddress, msg wasmTypes.CosmosMsg) ([]sdk.Msg, error) { +func (e MessageEncoders) Encode(contractAddr sdk.AccAddress, msg wasmvmtypes.CosmosMsg) ([]sdk.Msg, error) { switch { case msg.Bank != nil: return e.Bank(contractAddr, msg.Bank) @@ -80,7 +80,7 @@ func (e MessageEncoders) Encode(contractAddr sdk.AccAddress, msg wasmTypes.Cosmo return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Wasm") } -func EncodeBankMsg(sender sdk.AccAddress, msg *wasmTypes.BankMsg) ([]sdk.Msg, error) { +func EncodeBankMsg(sender sdk.AccAddress, msg *wasmvmtypes.BankMsg) ([]sdk.Msg, error) { if msg.Send == nil { return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Unknown variant of Bank") } @@ -103,7 +103,7 @@ func NoCustomMsg(sender sdk.AccAddress, msg json.RawMessage) ([]sdk.Msg, error) return nil, sdkerrors.Wrap(types.ErrInvalidMsg, "Custom variant not supported") } -func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmTypes.StakingMsg) ([]sdk.Msg, error) { +func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmvmtypes.StakingMsg) ([]sdk.Msg, error) { switch { case msg.Delegate != nil: coin, err := convertWasmCoinToSdkCoin(msg.Delegate.Amount) @@ -160,7 +160,7 @@ func EncodeStakingMsg(sender sdk.AccAddress, msg *wasmTypes.StakingMsg) ([]sdk.M } } -func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, error) { +func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmvmtypes.WasmMsg) ([]sdk.Msg, error) { switch { case msg.Execute != nil: contractAddr, err := sdk.AccAddressFromBech32(msg.Execute.ContractAddr) @@ -199,7 +199,7 @@ func EncodeWasmMsg(sender sdk.AccAddress, msg *wasmTypes.WasmMsg) ([]sdk.Msg, er } } -func (h MessageHandler) Dispatch(ctx sdk.Context, contractAddr sdk.AccAddress, msg wasmTypes.CosmosMsg) error { +func (h MessageHandler) Dispatch(ctx sdk.Context, contractAddr sdk.AccAddress, msg wasmvmtypes.CosmosMsg) error { sdkMsgs, err := h.encoders.Encode(contractAddr, msg) if err != nil { return err @@ -243,7 +243,7 @@ func (h MessageHandler) handleSdkMessage(ctx sdk.Context, contractAddr sdk.Addre return nil } -func convertWasmCoinsToSdkCoins(coins []wasmTypes.Coin) (sdk.Coins, error) { +func convertWasmCoinsToSdkCoins(coins []wasmvmtypes.Coin) (sdk.Coins, error) { var toSend sdk.Coins for _, coin := range coins { c, err := convertWasmCoinToSdkCoin(coin) @@ -255,7 +255,7 @@ func convertWasmCoinsToSdkCoins(coins []wasmTypes.Coin) (sdk.Coins, error) { return toSend, nil } -func convertWasmCoinToSdkCoin(coin wasmTypes.Coin) (sdk.Coin, error) { +func convertWasmCoinToSdkCoin(coin wasmvmtypes.Coin) (sdk.Coin, error) { amount, ok := sdk.NewIntFromString(coin.Amount) if !ok { return sdk.Coin{}, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, coin.Amount+coin.Denom) diff --git a/x/wasm/internal/keeper/handler_plugin_test.go b/x/wasm/internal/keeper/handler_plugin_test.go index 5d2883704d..d3474e97ab 100644 --- a/x/wasm/internal/keeper/handler_plugin_test.go +++ b/x/wasm/internal/keeper/handler_plugin_test.go @@ -5,8 +5,8 @@ import ( "fmt" "testing" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types" @@ -28,7 +28,7 @@ func TestEncoding(t *testing.T) { cases := map[string]struct { sender sdk.AccAddress - input wasmTypes.CosmosMsg + input wasmvmtypes.CosmosMsg // set if valid output []sdk.Msg // set if invalid @@ -36,12 +36,12 @@ func TestEncoding(t *testing.T) { }{ "simple send": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Bank: &wasmTypes.BankMsg{ - Send: &wasmTypes.SendMsg{ + input: wasmvmtypes.CosmosMsg{ + Bank: &wasmvmtypes.BankMsg{ + Send: &wasmvmtypes.SendMsg{ FromAddress: addr1.String(), ToAddress: addr2.String(), - Amount: []wasmTypes.Coin{ + Amount: []wasmvmtypes.Coin{ { Denom: "uatom", Amount: "12345", @@ -67,12 +67,12 @@ func TestEncoding(t *testing.T) { }, "invalid send amount": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Bank: &wasmTypes.BankMsg{ - Send: &wasmTypes.SendMsg{ + input: wasmvmtypes.CosmosMsg{ + Bank: &wasmvmtypes.BankMsg{ + Send: &wasmvmtypes.SendMsg{ FromAddress: addr1.String(), ToAddress: addr2.String(), - Amount: []wasmTypes.Coin{ + Amount: []wasmvmtypes.Coin{ { Denom: "uatom", Amount: "123.456", @@ -85,12 +85,12 @@ func TestEncoding(t *testing.T) { }, "invalid address": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Bank: &wasmTypes.BankMsg{ - Send: &wasmTypes.SendMsg{ + input: wasmvmtypes.CosmosMsg{ + Bank: &wasmvmtypes.BankMsg{ + Send: &wasmvmtypes.SendMsg{ FromAddress: addr1.String(), ToAddress: invalidAddr, - Amount: []wasmTypes.Coin{ + Amount: []wasmvmtypes.Coin{ { Denom: "uatom", Amount: "7890", @@ -112,13 +112,13 @@ func TestEncoding(t *testing.T) { }, "wasm execute": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Wasm: &wasmTypes.WasmMsg{ - Execute: &wasmTypes.ExecuteMsg{ + input: wasmvmtypes.CosmosMsg{ + Wasm: &wasmvmtypes.WasmMsg{ + Execute: &wasmvmtypes.ExecuteMsg{ ContractAddr: addr2.String(), Msg: jsonMsg, - Send: []wasmTypes.Coin{ - wasmTypes.NewCoin(12, "eth"), + Send: []wasmvmtypes.Coin{ + wasmvmtypes.NewCoin(12, "eth"), }, }, }, @@ -134,13 +134,13 @@ func TestEncoding(t *testing.T) { }, "wasm instantiate": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Wasm: &wasmTypes.WasmMsg{ - Instantiate: &wasmTypes.InstantiateMsg{ + input: wasmvmtypes.CosmosMsg{ + Wasm: &wasmvmtypes.WasmMsg{ + Instantiate: &wasmvmtypes.InstantiateMsg{ CodeID: 7, Msg: jsonMsg, - Send: []wasmTypes.Coin{ - wasmTypes.NewCoin(123, "eth"), + Send: []wasmvmtypes.Coin{ + wasmvmtypes.NewCoin(123, "eth"), }, }, }, @@ -158,11 +158,11 @@ func TestEncoding(t *testing.T) { }, "staking delegate": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Delegate: &wasmTypes.DelegateMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Delegate: &wasmvmtypes.DelegateMsg{ Validator: valAddr.String(), - Amount: wasmTypes.NewCoin(777, "stake"), + Amount: wasmvmtypes.NewCoin(777, "stake"), }, }, }, @@ -176,11 +176,11 @@ func TestEncoding(t *testing.T) { }, "staking delegate to non-validator": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Delegate: &wasmTypes.DelegateMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Delegate: &wasmvmtypes.DelegateMsg{ Validator: addr2.String(), - Amount: wasmTypes.NewCoin(777, "stake"), + Amount: wasmvmtypes.NewCoin(777, "stake"), }, }, }, @@ -195,11 +195,11 @@ func TestEncoding(t *testing.T) { }, "staking undelegate": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Undelegate: &wasmTypes.UndelegateMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Undelegate: &wasmvmtypes.UndelegateMsg{ Validator: valAddr.String(), - Amount: wasmTypes.NewCoin(555, "stake"), + Amount: wasmvmtypes.NewCoin(555, "stake"), }, }, }, @@ -213,12 +213,12 @@ func TestEncoding(t *testing.T) { }, "staking redelegate": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Redelegate: &wasmTypes.RedelegateMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Redelegate: &wasmvmtypes.RedelegateMsg{ SrcValidator: valAddr.String(), DstValidator: valAddr2.String(), - Amount: wasmTypes.NewCoin(222, "stake"), + Amount: wasmvmtypes.NewCoin(222, "stake"), }, }, }, @@ -233,9 +233,9 @@ func TestEncoding(t *testing.T) { }, "staking withdraw (implicit recipient)": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Withdraw: &wasmTypes.WithdrawMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Withdraw: &wasmvmtypes.WithdrawMsg{ Validator: valAddr2.String(), }, }, @@ -253,9 +253,9 @@ func TestEncoding(t *testing.T) { }, "staking withdraw (explicit recipient)": { sender: addr1, - input: wasmTypes.CosmosMsg{ - Staking: &wasmTypes.StakingMsg{ - Withdraw: &wasmTypes.WithdrawMsg{ + input: wasmvmtypes.CosmosMsg{ + Staking: &wasmvmtypes.StakingMsg{ + Withdraw: &wasmvmtypes.WithdrawMsg{ Validator: valAddr2.String(), Recipient: addr2.String(), }, diff --git a/x/wasm/internal/keeper/keeper.go b/x/wasm/internal/keeper/keeper.go index d01b5f9cb3..cca54b8d02 100644 --- a/x/wasm/internal/keeper/keeper.go +++ b/x/wasm/internal/keeper/keeper.go @@ -5,9 +5,9 @@ import ( "encoding/binary" "path/filepath" - wasm "github.com/CosmWasm/go-cosmwasm" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmvm "github.com/CosmWasm/wasmvm" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/cosmos/cosmos-sdk/codec" "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" @@ -50,7 +50,7 @@ type Keeper struct { wasmer types.WasmerEngine queryPlugins QueryPlugins messenger MessageHandler - // queryGasLimit is the max wasm gas that can be spent on executing a query with a contract + // queryGasLimit is the max wasmvm gas that can be spent on executing a query with a contract queryGasLimit uint64 authZPolicy AuthorizationPolicy paramSpace paramtypes.Subspace @@ -73,7 +73,7 @@ func NewKeeper( customEncoders *MessageEncoders, customPlugins *QueryPlugins, ) Keeper { - wasmer, err := wasm.NewWasmer(filepath.Join(homeDir, "wasm"), supportedFeatures) + wasmer, err := wasmvm.NewVM(filepath.Join(homeDir, "wasm"), supportedFeatures, wasmConfig.ContractDebugMode, wasmConfig.MemoryCacheSize) if err != nil { panic(err) } @@ -566,7 +566,7 @@ func (k Keeper) GetByteCode(ctx sdk.Context, codeID uint64) ([]byte, error) { return k.wasmer.GetCode(codeInfo.CodeHash) } -func (k Keeper) dispatchMessages(ctx sdk.Context, contractAddr sdk.AccAddress, msgs []wasmTypes.CosmosMsg) error { +func (k Keeper) dispatchMessages(ctx sdk.Context, contractAddr sdk.AccAddress, msgs []wasmvmtypes.CosmosMsg) error { for _, msg := range msgs { if err := k.messenger.Dispatch(ctx, contractAddr, msg); err != nil { return err @@ -679,7 +679,7 @@ type MultipiedGasMeter struct { originalMeter sdk.GasMeter } -var _ wasm.GasMeter = MultipiedGasMeter{} +var _ wasmvm.GasMeter = MultipiedGasMeter{} func (m MultipiedGasMeter) GasConsumed() sdk.Gas { return m.originalMeter.GasConsumed() * GasMultiplier diff --git a/x/wasm/internal/keeper/query_plugins.go b/x/wasm/internal/keeper/query_plugins.go index 20a97830cb..a62b1745a5 100644 --- a/x/wasm/internal/keeper/query_plugins.go +++ b/x/wasm/internal/keeper/query_plugins.go @@ -3,7 +3,7 @@ package keeper import ( "encoding/json" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" bankkeeper "github.com/cosmos/cosmos-sdk/x/bank/keeper" @@ -18,9 +18,9 @@ type QueryHandler struct { Plugins QueryPlugins } -var _ wasmTypes.Querier = QueryHandler{} +var _ wasmvmtypes.Querier = QueryHandler{} -func (q QueryHandler) Query(request wasmTypes.QueryRequest, gasLimit uint64) ([]byte, error) { +func (q QueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ([]byte, error) { // set a limit for a subctx sdkGas := gasLimit / GasMultiplier subctx := q.Ctx.WithGasMeter(sdk.NewGasMeter(sdkGas)) @@ -43,7 +43,7 @@ func (q QueryHandler) Query(request wasmTypes.QueryRequest, gasLimit uint64) ([] if request.Wasm != nil { return q.Plugins.Wasm(subctx, request.Wasm) } - return nil, wasmTypes.Unknown{} + return nil, wasmvmtypes.Unknown{} } func (q QueryHandler) GasConsumed() uint64 { @@ -53,10 +53,10 @@ func (q QueryHandler) GasConsumed() uint64 { type CustomQuerier func(ctx sdk.Context, request json.RawMessage) ([]byte, error) type QueryPlugins struct { - Bank func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) + Bank func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) Custom CustomQuerier - Staking func(ctx sdk.Context, request *wasmTypes.StakingQuery) ([]byte, error) - Wasm func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) + Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) + Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) } func DefaultQueryPlugins(bank bankkeeper.ViewKeeper, staking stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, wasm *Keeper) QueryPlugins { @@ -88,15 +88,15 @@ func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins { return e } -func BankQuerier(bankKeeper bankkeeper.ViewKeeper) func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmTypes.BankQuery) ([]byte, error) { +func BankQuerier(bankKeeper bankkeeper.ViewKeeper) func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error) { + return func(ctx sdk.Context, request *wasmvmtypes.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 := bankKeeper.GetAllBalances(ctx, addr) - res := wasmTypes.AllBalancesResponse{ + res := wasmvmtypes.AllBalancesResponse{ Amount: convertSdkCoinsToWasmCoins(coins), } return json.Marshal(res) @@ -108,27 +108,27 @@ func BankQuerier(bankKeeper bankkeeper.ViewKeeper) func(ctx sdk.Context, request } coins := bankKeeper.GetAllBalances(ctx, addr) amount := coins.AmountOf(request.Balance.Denom) - res := wasmTypes.BalanceResponse{ - Amount: wasmTypes.Coin{ + res := wasmvmtypes.BalanceResponse{ + Amount: wasmvmtypes.Coin{ Denom: request.Balance.Denom, Amount: amount.String(), }, } return json.Marshal(res) } - return nil, wasmTypes.UnsupportedRequest{Kind: "unknown BankQuery variant"} + return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown BankQuery variant"} } } func NoCustomQuerier(sdk.Context, json.RawMessage) ([]byte, error) { - return nil, wasmTypes.UnsupportedRequest{Kind: "custom"} + return nil, wasmvmtypes.UnsupportedRequest{Kind: "custom"} } -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) { +func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper) func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { + return func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error) { if request.BondedDenom != nil { denom := keeper.BondDenom(ctx) - res := wasmTypes.BondedDenomResponse{ + res := wasmvmtypes.BondedDenomResponse{ Denom: denom, } return json.Marshal(res) @@ -136,16 +136,16 @@ func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.K if request.Validators != nil { validators := keeper.GetBondedValidatorsByPower(ctx) //validators := keeper.GetAllValidators(ctx) - wasmVals := make([]wasmTypes.Validator, len(validators)) + wasmVals := make([]wasmvmtypes.Validator, len(validators)) for i, v := range validators { - wasmVals[i] = wasmTypes.Validator{ + wasmVals[i] = wasmvmtypes.Validator{ Address: v.OperatorAddress, Commission: v.Commission.Rate.String(), MaxCommission: v.Commission.MaxRate.String(), MaxChangeRate: v.Commission.MaxChangeRate.String(), } } - res := wasmTypes.ValidatorsResponse{ + res := wasmvmtypes.ValidatorsResponse{ Validators: wasmVals, } return json.Marshal(res) @@ -160,7 +160,7 @@ func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.K if err != nil { return nil, err } - res := wasmTypes.AllDelegationsResponse{ + res := wasmvmtypes.AllDelegationsResponse{ Delegations: delegations, } return json.Marshal(res) @@ -175,7 +175,7 @@ func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.K return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, request.Delegation.Validator) } - var res wasmTypes.DelegationResponse + var res wasmvmtypes.DelegationResponse d, found := keeper.GetDelegation(ctx, delegator, validator) if found { res.Delegation, err = sdkToFullDelegation(ctx, keeper, distKeeper, d) @@ -185,12 +185,12 @@ func StakingQuerier(keeper stakingkeeper.Keeper, distKeeper distributionkeeper.K } return json.Marshal(res) } - return nil, wasmTypes.UnsupportedRequest{Kind: "unknown Staking variant"} + return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown Staking variant"} } } -func sdkToDelegations(ctx sdk.Context, keeper stakingkeeper.Keeper, delegations []stakingtypes.Delegation) (wasmTypes.Delegations, error) { - result := make([]wasmTypes.Delegation, len(delegations)) +func sdkToDelegations(ctx sdk.Context, keeper stakingkeeper.Keeper, delegations []stakingtypes.Delegation) (wasmvmtypes.Delegations, error) { + result := make([]wasmvmtypes.Delegation, len(delegations)) bondDenom := keeper.BondDenom(ctx) for i, d := range delegations { @@ -211,7 +211,7 @@ func sdkToDelegations(ctx sdk.Context, keeper stakingkeeper.Keeper, delegations } amount := sdk.NewCoin(bondDenom, val.TokensFromShares(d.Shares).TruncateInt()) - result[i] = wasmTypes.Delegation{ + result[i] = wasmvmtypes.Delegation{ Delegator: delAddr.String(), Validator: valAddr.String(), Amount: convertSdkCoinToWasmCoin(amount), @@ -220,7 +220,7 @@ func sdkToDelegations(ctx sdk.Context, keeper stakingkeeper.Keeper, delegations return result, nil } -func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) (*wasmTypes.FullDelegation, error) { +func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) (*wasmvmtypes.FullDelegation, error) { delAddr, err := sdk.AccAddressFromBech32(delegation.DelegatorAddress) if err != nil { return nil, sdkerrors.Wrap(err, "delegator address") @@ -243,7 +243,7 @@ func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeepe // if this (val, delegate) pair is receiving a redelegation, it cannot redelegate more // otherwise, it can redelegate the full amount // (there are cases of partial funds redelegated, but this is a start) - redelegateCoins := wasmTypes.NewCoin(0, bondDenom) + redelegateCoins := wasmvmtypes.NewCoin(0, bondDenom) if !keeper.HasReceivingRedelegation(ctx, delAddr, valAddr) { redelegateCoins = delegationCoins } @@ -257,7 +257,7 @@ func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeepe return nil, err } - return &wasmTypes.FullDelegation{ + return &wasmvmtypes.FullDelegation{ Delegator: delAddr.String(), Validator: valAddr.String(), Amount: delegationCoins, @@ -268,7 +268,7 @@ func sdkToFullDelegation(ctx sdk.Context, keeper stakingkeeper.Keeper, distKeepe // FIXME: simplify this enormously when // https://github.com/cosmos/cosmos-sdk/issues/7466 is merged -func getAccumulatedRewards(ctx sdk.Context, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) ([]wasmTypes.Coin, error) { +func getAccumulatedRewards(ctx sdk.Context, distKeeper distributionkeeper.Keeper, delegation stakingtypes.Delegation) ([]wasmvmtypes.Coin, error) { // Try to get *delegator* reward info! params := distributiontypes.QueryDelegationRewardsRequest{ DelegatorAddress: delegation.DelegatorAddress, @@ -280,10 +280,10 @@ func getAccumulatedRewards(ctx sdk.Context, distKeeper distributionkeeper.Keeper return nil, err } - // now we have it, convert it into wasmTypes - rewards := make([]wasmTypes.Coin, len(qres.Rewards)) + // now we have it, convert it into wasmvm types + rewards := make([]wasmvmtypes.Coin, len(qres.Rewards)) for i, r := range qres.Rewards { - rewards[i] = wasmTypes.Coin{ + rewards[i] = wasmvmtypes.Coin{ Denom: r.Denom, Amount: r.Amount.TruncateInt().String(), } @@ -291,8 +291,8 @@ func getAccumulatedRewards(ctx sdk.Context, distKeeper distributionkeeper.Keeper return rewards, nil } -func WasmQuerier(wasm *Keeper) func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) { - return func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) { +func WasmQuerier(wasm *Keeper) func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { + return func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { if request.Smart != nil { addr, err := sdk.AccAddressFromBech32(request.Smart.ContractAddr) if err != nil { @@ -307,20 +307,20 @@ func WasmQuerier(wasm *Keeper) func(ctx sdk.Context, request *wasmTypes.WasmQuer } return wasm.QueryRaw(ctx, addr, request.Raw.Key), nil } - return nil, wasmTypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"} + return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown WasmQuery variant"} } } -func convertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmTypes.Coins { - converted := make(wasmTypes.Coins, len(coins)) +func convertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins { + converted := make(wasmvmtypes.Coins, len(coins)) for i, c := range coins { converted[i] = convertSdkCoinToWasmCoin(c) } return converted } -func convertSdkCoinToWasmCoin(coin sdk.Coin) wasmTypes.Coin { - return wasmTypes.Coin{ +func convertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin { + return wasmvmtypes.Coin{ Denom: coin.Denom, Amount: coin.Amount.String(), } diff --git a/x/wasm/internal/keeper/recurse_test.go b/x/wasm/internal/keeper/recurse_test.go index 3abba76a09..eddec5c1ce 100644 --- a/x/wasm/internal/keeper/recurse_test.go +++ b/x/wasm/internal/keeper/recurse_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "testing" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,9 +38,9 @@ var totalWasmQueryCounter int 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) - var realWasmQuerier func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) + var realWasmQuerier func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) countingQuerier := &QueryPlugins{ - Wasm: func(ctx sdk.Context, request *wasmTypes.WasmQuery) ([]byte, error) { + Wasm: func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error) { totalWasmQueryCounter++ return realWasmQuerier(ctx, request) }, diff --git a/x/wasm/internal/keeper/reflect_test.go b/x/wasm/internal/keeper/reflect_test.go index 6c5542a934..bded56b3bb 100644 --- a/x/wasm/internal/keeper/reflect_test.go +++ b/x/wasm/internal/keeper/reflect_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" sdk "github.com/cosmos/cosmos-sdk/types" @@ -32,7 +32,7 @@ type ownerPayload struct { } type reflectPayload struct { - Msgs []wasmTypes.CosmosMsg `json:"msgs"` + Msgs []wasmvmtypes.CosmosMsg `json:"msgs"` } // MaskQueryMsg is used to encode query messages @@ -43,7 +43,7 @@ type MaskQueryMsg struct { } type ChainQuery struct { - Request *wasmTypes.QueryRequest `json:"request,omitempty"` + Request *wasmvmtypes.QueryRequest `json:"request,omitempty"` } type Text struct { @@ -123,12 +123,12 @@ func TestMaskReflectContractSend(t *testing.T) { // this should reduce the mask balance by 14k (to 26k) // this 14k is added to the escrow, then the entire balance is sent to bob (total: 39k) approveMsg := []byte(`{"release":{}}`) - msgs := []wasmTypes.CosmosMsg{{ - Wasm: &wasmTypes.WasmMsg{ - Execute: &wasmTypes.ExecuteMsg{ + msgs := []wasmvmtypes.CosmosMsg{{ + Wasm: &wasmvmtypes.WasmMsg{ + Execute: &wasmvmtypes.ExecuteMsg{ ContractAddr: escrowAddr.String(), Msg: approveMsg, - Send: []wasmTypes.Coin{{ + Send: []wasmvmtypes.Coin{{ Denom: "denom", Amount: "14000", }}, @@ -193,12 +193,12 @@ func TestMaskReflectCustomMsg(t *testing.T) { checkAccount(t, ctx, accKeeper, bankKeeper, fred, nil) // bob can send contract's tokens to fred (using SendMsg) - msgs := []wasmTypes.CosmosMsg{{ - Bank: &wasmTypes.BankMsg{ - Send: &wasmTypes.SendMsg{ + msgs := []wasmvmtypes.CosmosMsg{{ + Bank: &wasmvmtypes.BankMsg{ + Send: &wasmvmtypes.SendMsg{ FromAddress: contractAddr.String(), ToAddress: fred.String(), - Amount: []wasmTypes.Coin{{ + Amount: []wasmvmtypes.Coin{{ Denom: "denom", Amount: "15000", }}, @@ -231,7 +231,7 @@ func TestMaskReflectCustomMsg(t *testing.T) { require.NoError(t, err) reflectOpaque := MaskHandleMsg{ Reflect: &reflectPayload{ - Msgs: []wasmTypes.CosmosMsg{opaque}, + Msgs: []wasmvmtypes.CosmosMsg{opaque}, }, } reflectOpaqueBz, err := json.Marshal(reflectOpaque) @@ -337,8 +337,8 @@ func TestMaskReflectWasmQueries(t *testing.T) { require.Equal(t, stateRes.Owner, []byte(creator)) // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectOwnerQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Wasm: &wasmTypes.WasmQuery{ - Smart: &wasmTypes.SmartQuery{ + reflectOwnerQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ + Smart: &wasmvmtypes.SmartQuery{ ContractAddr: maskAddr.String(), Msg: ownerQuery, }, @@ -354,8 +354,8 @@ func TestMaskReflectWasmQueries(t *testing.T) { require.Equal(t, reflectOwnerRes.Owner, creator.String()) // and with queryRaw - reflectStateQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Wasm: &wasmTypes.WasmQuery{ - Raw: &wasmTypes.RawQuery{ + reflectStateQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ + Raw: &wasmvmtypes.RawQuery{ ContractAddr: maskAddr.String(), Key: configKey, }, @@ -398,8 +398,8 @@ func TestWasmRawQueryWithNil(t *testing.T) { require.Nil(t, raw) // and with queryRaw - reflectQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Wasm: &wasmTypes.WasmQuery{ - Raw: &wasmTypes.RawQuery{ + reflectQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Wasm: &wasmvmtypes.WasmQuery{ + Raw: &wasmvmtypes.RawQuery{ ContractAddr: maskAddr.String(), Key: missingKey, }, @@ -441,19 +441,19 @@ type maskCustomMsg struct { // toMaskRawMsg encodes an sdk msg using any type with json encoding. // Then wraps it as an opaque message -func toMaskRawMsg(cdc codec.Marshaler, msg sdk.Msg) (wasmTypes.CosmosMsg, error) { +func toMaskRawMsg(cdc codec.Marshaler, msg sdk.Msg) (wasmvmtypes.CosmosMsg, error) { any, err := codectypes.NewAnyWithValue(msg) if err != nil { - return wasmTypes.CosmosMsg{}, err + return wasmvmtypes.CosmosMsg{}, err } rawBz, err := cdc.MarshalJSON(any) if err != nil { - return wasmTypes.CosmosMsg{}, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) + return wasmvmtypes.CosmosMsg{}, sdkerrors.Wrap(sdkerrors.ErrJSONMarshal, err.Error()) } customMsg, err := json.Marshal(maskCustomMsg{ Raw: rawBz, }) - res := wasmTypes.CosmosMsg{ + res := wasmvmtypes.CosmosMsg{ Custom: customMsg, } return res, nil diff --git a/x/wasm/internal/keeper/staking_test.go b/x/wasm/internal/keeper/staking_test.go index a0ccf57e50..2b6cff5940 100644 --- a/x/wasm/internal/keeper/staking_test.go +++ b/x/wasm/internal/keeper/staking_test.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "testing" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/crypto/keys/ed25519" sdk "github.com/cosmos/cosmos-sdk/types" @@ -453,7 +453,7 @@ func TestQueryStakingInfo(t *testing.T) { // STEP 3: now, let's reflect some queries. // let's get the bonded denom - reflectBondedQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Staking: &wasmTypes.StakingQuery{ + reflectBondedQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ BondedDenom: &struct{}{}, }}}} reflectBondedBin := buildMaskQuery(t, &reflectBondedQuery) @@ -462,20 +462,20 @@ func TestQueryStakingInfo(t *testing.T) { // first we pull out the data from chain response, before parsing the original response var reflectRes ChainResponse mustParse(t, res, &reflectRes) - var bondedRes wasmTypes.BondedDenomResponse + var bondedRes wasmvmtypes.BondedDenomResponse mustParse(t, reflectRes.Data, &bondedRes) assert.Equal(t, "stake", bondedRes.Denom) // now, let's reflect a smart query into the x/wasm handlers and see if we get the same result - reflectValidatorsQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Staking: &wasmTypes.StakingQuery{ - Validators: &wasmTypes.ValidatorsQuery{}, + reflectValidatorsQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ + Validators: &wasmvmtypes.ValidatorsQuery{}, }}}} reflectValidatorsBin := buildMaskQuery(t, &reflectValidatorsQuery) res, err = keeper.QuerySmart(ctx, maskAddr, reflectValidatorsBin) require.NoError(t, err) // first we pull out the data from chain response, before parsing the original response mustParse(t, res, &reflectRes) - var validatorRes wasmTypes.ValidatorsResponse + var validatorRes wasmvmtypes.ValidatorsResponse mustParse(t, reflectRes.Data, &validatorRes) require.Len(t, validatorRes.Validators, 1) valInfo := validatorRes.Validators[0] @@ -486,8 +486,8 @@ func TestQueryStakingInfo(t *testing.T) { require.Contains(t, valInfo.MaxChangeRate, "0.010") // test to get all my delegations - reflectAllDelegationsQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Staking: &wasmTypes.StakingQuery{ - AllDelegations: &wasmTypes.AllDelegationsQuery{ + reflectAllDelegationsQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ + AllDelegations: &wasmvmtypes.AllDelegationsQuery{ Delegator: contractAddr.String(), }, }}}} @@ -496,7 +496,7 @@ func TestQueryStakingInfo(t *testing.T) { require.NoError(t, err) // first we pull out the data from chain response, before parsing the original response mustParse(t, res, &reflectRes) - var allDelegationsRes wasmTypes.AllDelegationsResponse + var allDelegationsRes wasmvmtypes.AllDelegationsResponse mustParse(t, reflectRes.Data, &allDelegationsRes) require.Len(t, allDelegationsRes.Delegations, 1) delInfo := allDelegationsRes.Delegations[0] @@ -509,8 +509,8 @@ func TestQueryStakingInfo(t *testing.T) { require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) // test to get one delegations - reflectDelegationQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmTypes.QueryRequest{Staking: &wasmTypes.StakingQuery{ - Delegation: &wasmTypes.DelegationQuery{ + reflectDelegationQuery := MaskQueryMsg{Chain: &ChainQuery{Request: &wasmvmtypes.QueryRequest{Staking: &wasmvmtypes.StakingQuery{ + Delegation: &wasmvmtypes.DelegationQuery{ Validator: valAddr.String(), Delegator: contractAddr.String(), }, @@ -520,7 +520,7 @@ func TestQueryStakingInfo(t *testing.T) { require.NoError(t, err) // first we pull out the data from chain response, before parsing the original response mustParse(t, res, &reflectRes) - var delegationRes wasmTypes.DelegationResponse + var delegationRes wasmvmtypes.DelegationResponse mustParse(t, reflectRes.Data, &delegationRes) assert.NotEmpty(t, delegationRes.Delegation) delInfo2 := delegationRes.Delegation @@ -532,10 +532,10 @@ func TestQueryStakingInfo(t *testing.T) { require.Equal(t, funds[0].Denom, delInfo2.Amount.Denom) require.Equal(t, funds[0].Amount.String(), delInfo2.Amount.Amount) - require.Equal(t, wasmTypes.NewCoin(200000, "stake"), delInfo2.CanRedelegate) + require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo2.CanRedelegate) require.Len(t, delInfo2.AccumulatedRewards, 1) // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmTypes.NewCoin(36000, "stake"), delInfo2.AccumulatedRewards[0]) + require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo2.AccumulatedRewards[0]) // ensure rewards did not change when querying (neither amount nor period) finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) @@ -578,15 +578,15 @@ func TestQueryStakingPlugin(t *testing.T) { origReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) // Step 2: Try out the query plugins - query := wasmTypes.StakingQuery{ - Delegation: &wasmTypes.DelegationQuery{ + query := wasmvmtypes.StakingQuery{ + Delegation: &wasmvmtypes.DelegationQuery{ Delegator: contractAddr.String(), Validator: valAddr.String(), }, } raw, err := StakingQuerier(stakingKeeper, distKeeper)(ctx, &query) require.NoError(t, err) - var res wasmTypes.DelegationResponse + var res wasmvmtypes.DelegationResponse mustParse(t, raw, &res) assert.NotEmpty(t, res.Delegation) delInfo := res.Delegation @@ -598,10 +598,10 @@ func TestQueryStakingPlugin(t *testing.T) { require.Equal(t, funds[0].Denom, delInfo.Amount.Denom) require.Equal(t, funds[0].Amount.String(), delInfo.Amount.Amount) - require.Equal(t, wasmTypes.NewCoin(200000, "stake"), delInfo.CanRedelegate) + require.Equal(t, wasmvmtypes.NewCoin(200000, "stake"), delInfo.CanRedelegate) require.Len(t, delInfo.AccumulatedRewards, 1) // see bonding above to see how we calculate 36000 (240000 / 6 - 10% commission) - require.Equal(t, wasmTypes.NewCoin(36000, "stake"), delInfo.AccumulatedRewards[0]) + require.Equal(t, wasmvmtypes.NewCoin(36000, "stake"), delInfo.AccumulatedRewards[0]) // ensure rewards did not change when querying (neither amount nor period) finalReward := distKeeper.GetValidatorCurrentRewards(ctx, valAddr) diff --git a/x/wasm/internal/keeper/test_common.go b/x/wasm/internal/keeper/test_common.go index 478ae02848..0388a40846 100644 --- a/x/wasm/internal/keeper/test_common.go +++ b/x/wasm/internal/keeper/test_common.go @@ -10,9 +10,9 @@ import ( "testing" "time" - "github.com/CosmWasm/go-cosmwasm" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/types" + "github.com/CosmWasm/wasmvm" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" @@ -422,10 +422,10 @@ var _ types.WasmerEngine = &MockWasmer{} // Without a stub function a panic is thrown. type MockWasmer struct { CreateFn func(code cosmwasm.WasmCode) (cosmwasm.CodeID, error) - InstantiateFn func(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.InitResponse, uint64, error) - ExecuteFn func(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.HandleResponse, uint64, error) - QueryFn func(code cosmwasm.CodeID, env wasmTypes.Env, queryMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) ([]byte, uint64, error) - MigrateFn func(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, migrateMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.MigrateResponse, uint64, error) + InstantiateFn func(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.InitResponse, uint64, error) + ExecuteFn func(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.HandleResponse, uint64, error) + QueryFn func(code cosmwasm.CodeID, env wasmvmtypes.Env, queryMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) ([]byte, uint64, error) + MigrateFn func(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, migrateMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.MigrateResponse, uint64, error) GetCodeFn func(code cosmwasm.CodeID) (cosmwasm.WasmCode, error) CleanupFn func() } @@ -437,7 +437,7 @@ func (m *MockWasmer) Create(code cosmwasm.WasmCode) (cosmwasm.CodeID, error) { return m.CreateFn(code) } -func (m *MockWasmer) Instantiate(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.InitResponse, uint64, error) { +func (m *MockWasmer) Instantiate(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.InitResponse, uint64, error) { if m.InstantiateFn == nil { panic("not supposed to be called!") } @@ -445,21 +445,21 @@ func (m *MockWasmer) Instantiate(code cosmwasm.CodeID, env wasmTypes.Env, info w return m.InstantiateFn(code, env, info, initMsg, store, goapi, querier, gasMeter, gasLimit) } -func (m *MockWasmer) Execute(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.HandleResponse, uint64, error) { +func (m *MockWasmer) Execute(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.HandleResponse, uint64, error) { if m.ExecuteFn == nil { panic("not supposed to be called!") } return m.ExecuteFn(code, env, info, executeMsg, store, goapi, querier, gasMeter, gasLimit) } -func (m *MockWasmer) Query(code cosmwasm.CodeID, env wasmTypes.Env, queryMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) ([]byte, uint64, error) { +func (m *MockWasmer) Query(code cosmwasm.CodeID, env wasmvmtypes.Env, queryMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) ([]byte, uint64, error) { if m.QueryFn == nil { panic("not supposed to be called!") } return m.QueryFn(code, env, queryMsg, store, goapi, querier, gasMeter, gasLimit) } -func (m *MockWasmer) Migrate(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, migrateMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.MigrateResponse, uint64, error) { +func (m *MockWasmer) Migrate(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, migrateMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.MigrateResponse, uint64, error) { if m.MigrateFn == nil { panic("not supposed to be called!") } @@ -490,16 +490,16 @@ func selfCallingInstMockWasmer(executeCalled *bool) *MockWasmer { anyCodeID := bytes.Repeat([]byte{0x1}, 32) return anyCodeID, nil }, - InstantiateFn: func(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.InitResponse, uint64, error) { - return &wasmTypes.InitResponse{ - Messages: []wasmTypes.CosmosMsg{ - {Wasm: &wasmTypes.WasmMsg{Execute: &wasmTypes.ExecuteMsg{ContractAddr: env.Contract.Address, Msg: []byte(`{}`)}}}, + InstantiateFn: func(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, initMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.InitResponse, uint64, error) { + return &wasmvmtypes.InitResponse{ + Messages: []wasmvmtypes.CosmosMsg{ + {Wasm: &wasmvmtypes.WasmMsg{Execute: &wasmvmtypes.ExecuteMsg{ContractAddr: env.Contract.Address, Msg: []byte(`{}`)}}}, }, }, 1, nil }, - ExecuteFn: func(code cosmwasm.CodeID, env wasmTypes.Env, info wasmTypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmTypes.HandleResponse, uint64, error) { + ExecuteFn: func(code cosmwasm.CodeID, env wasmvmtypes.Env, info wasmvmtypes.MessageInfo, executeMsg []byte, store cosmwasm.KVStore, goapi cosmwasm.GoAPI, querier cosmwasm.Querier, gasMeter cosmwasm.GasMeter, gasLimit uint64) (*wasmvmtypes.HandleResponse, uint64, error) { *executeCalled = true - return &wasmTypes.HandleResponse{}, 1, nil + return &wasmvmtypes.HandleResponse{}, 1, nil }, } } diff --git a/x/wasm/internal/types/types.go b/x/wasm/internal/types/types.go index ba04502d1a..f91e53b510 100644 --- a/x/wasm/internal/types/types.go +++ b/x/wasm/internal/types/types.go @@ -1,13 +1,16 @@ package types import ( - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" ) -const defaultLRUCacheSize = uint64(0) -const defaultQueryGasLimit = uint64(3000000) +const ( + defaultMemoryCacheSize uint32 = 100 // in MiB + defaultQueryGasLimit uint64 = 3000000 + defaultContractDebugMode = false +) func (m Model) ValidateBasic() error { if len(m.Key) == 0 { @@ -137,7 +140,7 @@ func NewAbsoluteTxPosition(ctx sdk.Context) *AbsoluteTxPosition { } // NewEnv initializes the environment for a contract instance -func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmTypes.Env { +func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmvmtypes.Env { // safety checks before casting below if ctx.BlockHeight() < 0 { panic("Block height must never be negative") @@ -147,14 +150,14 @@ func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmTypes.Env { panic("Block (unix) time must never be negative ") } nano := ctx.BlockTime().Nanosecond() - env := wasmTypes.Env{ - Block: wasmTypes.BlockInfo{ + env := wasmvmtypes.Env{ + Block: wasmvmtypes.BlockInfo{ Height: uint64(ctx.BlockHeight()), Time: uint64(sec), TimeNanos: uint64(nano), ChainID: ctx.ChainID(), }, - Contract: wasmTypes.ContractInfo{ + Contract: wasmvmtypes.ContractInfo{ Address: contractAddr.String(), }, } @@ -162,17 +165,17 @@ func NewEnv(ctx sdk.Context, contractAddr sdk.AccAddress) wasmTypes.Env { } // NewInfo initializes the MessageInfo for a contract instance -func NewInfo(creator sdk.AccAddress, deposit sdk.Coins) wasmTypes.MessageInfo { - return wasmTypes.MessageInfo{ +func NewInfo(creator sdk.AccAddress, deposit sdk.Coins) wasmvmtypes.MessageInfo { + return wasmvmtypes.MessageInfo{ Sender: creator.String(), SentFunds: NewWasmCoins(deposit), } } // NewWasmCoins translates between Cosmos SDK coins and Wasm coins -func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmTypes.Coin) { +func NewWasmCoins(cosmosCoins sdk.Coins) (wasmCoins []wasmvmtypes.Coin) { for _, coin := range cosmosCoins { - wasmCoin := wasmTypes.Coin{ + wasmCoin := wasmvmtypes.Coin{ Denom: coin.Denom, Amount: coin.Amount.String(), } @@ -185,7 +188,7 @@ const CustomEventType = "wasm" const AttributeKeyContractAddr = "contract_address" // ParseEvents converts wasm LogAttributes into an sdk.Events (with 0 or 1 elements) -func ParseEvents(logs []wasmTypes.EventAttribute, contractAddr sdk.AccAddress) sdk.Events { +func ParseEvents(logs []wasmvmtypes.EventAttribute, contractAddr sdk.AccAddress) sdk.Events { if len(logs) == 0 { return nil } @@ -203,14 +206,18 @@ func ParseEvents(logs []wasmTypes.EventAttribute, contractAddr sdk.AccAddress) s // WasmConfig is the extra config required for wasm type WasmConfig struct { - SmartQueryGasLimit uint64 `mapstructure:"query_gas_limit"` - CacheSize uint64 `mapstructure:"lru_size"` + SmartQueryGasLimit uint64 + // MemoryCacheSize in MiB not bytes + MemoryCacheSize uint32 + // ContractDebugMode log what contract print + ContractDebugMode bool } // DefaultWasmConfig returns the default settings for WasmConfig func DefaultWasmConfig() WasmConfig { return WasmConfig{ SmartQueryGasLimit: defaultQueryGasLimit, - CacheSize: defaultLRUCacheSize, + MemoryCacheSize: defaultMemoryCacheSize, + ContractDebugMode: defaultContractDebugMode, } } diff --git a/x/wasm/internal/types/wasmer_engine.go b/x/wasm/internal/types/wasmer_engine.go index 8794b639d6..93490aec48 100644 --- a/x/wasm/internal/types/wasmer_engine.go +++ b/x/wasm/internal/types/wasmer_engine.go @@ -1,8 +1,8 @@ package types import ( - "github.com/CosmWasm/go-cosmwasm" - "github.com/CosmWasm/go-cosmwasm/types" + "github.com/CosmWasm/wasmvm" + "github.com/CosmWasm/wasmvm/types" ) // WasmerEngine defines the WASM contract runtime engine. diff --git a/x/wasm/module.go b/x/wasm/module.go index f0da3a7d01..feb01dee1e 100644 --- a/x/wasm/module.go +++ b/x/wasm/module.go @@ -12,11 +12,14 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" cdctypes "github.com/cosmos/cosmos-sdk/codec/types" + "github.com/cosmos/cosmos-sdk/server" + servertypes "github.com/cosmos/cosmos-sdk/server/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/cast" "github.com/spf13/cobra" abci "github.com/tendermint/tendermint/abci/types" ) @@ -26,6 +29,12 @@ var ( _ module.AppModuleBasic = AppModuleBasic{} ) +// Module init related flags +const ( + flagWasmMemoryCacheSize = "wasm.memory_cache_size" + flagWasmQueryGasLimit = "wasm.query_gas_limit" +) + // AppModuleBasic defines the basic application module used by the wasm module. type AppModuleBasic struct{} @@ -170,3 +179,35 @@ func (am AppModule) RegisterStoreDecoder(sdr sdk.StoreDecoderRegistry) { func (am AppModule) WeightedOperations(simState module.SimulationState) []simtypes.WeightedOperation { return nil } + +//____________________________________________________________________________ + +// AddModuleInitFlags implements servertypes.ModuleInitFlags interface. +func AddModuleInitFlags(startCmd *cobra.Command) { + defaults := DefaultWasmConfig() + startCmd.Flags().Uint32(flagWasmMemoryCacheSize, defaults.MemoryCacheSize, "Sets the size in MiB (NOT bytes) of an in-memory cache for Wasm modules. Set to 0 to disable.") + startCmd.Flags().Uint64(flagWasmQueryGasLimit, defaults.SmartQueryGasLimit, "Set the max gas that can be spent on executing a query with a Wasm contract") +} + +// ReadWasmConfig reads the wasm specifig configuration +func ReadWasmConfig(opts servertypes.AppOptions) (types.WasmConfig, error) { + cfg := types.DefaultWasmConfig() + var err error + if v := opts.Get(flagWasmMemoryCacheSize); v != nil { + if cfg.MemoryCacheSize, err = cast.ToUint32E(v); err != nil { + return cfg, err + } + } + if v := opts.Get(flagWasmQueryGasLimit); v != nil { + if cfg.SmartQueryGasLimit, err = cast.ToUint64E(v); err != nil { + return cfg, err + } + } + // attach contract debugging to global "trace" flag + if v := opts.Get(server.FlagTrace); v != nil { + if cfg.ContractDebugMode, err = cast.ToBoolE(v); err != nil { + return cfg, err + } + } + return cfg, nil +} diff --git a/x/wasm/module_test.go b/x/wasm/module_test.go index d01805f479..928f9d0662 100644 --- a/x/wasm/module_test.go +++ b/x/wasm/module_test.go @@ -6,8 +6,9 @@ import ( "io/ioutil" "testing" - wasmTypes "github.com/CosmWasm/go-cosmwasm/types" "github.com/CosmWasm/wasmd/x/wasm/internal/keeper" + "github.com/CosmWasm/wasmd/x/wasm/internal/types" + wasmvmtypes "github.com/CosmWasm/wasmvm/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/module" authkeeper "github.com/cosmos/cosmos-sdk/x/auth/keeper" @@ -130,9 +131,9 @@ type initMsg struct { } type state struct { - Verifier wasmTypes.CanonicalAddress `json:"verifier"` - Beneficiary wasmTypes.CanonicalAddress `json:"beneficiary"` - Funder wasmTypes.CanonicalAddress `json:"funder"` + Verifier wasmvmtypes.CanonicalAddress `json:"verifier"` + Beneficiary wasmvmtypes.CanonicalAddress `json:"beneficiary"` + Funder wasmvmtypes.CanonicalAddress `json:"funder"` } func TestHandleInstantiate(t *testing.T) { @@ -369,6 +370,59 @@ func TestHandleExecuteEscrow(t *testing.T) { assert.Equal(t, sdk.Coins(nil), data.bankKeeper.GetAllBalances(data.ctx, contractAcct.GetAddress())) } +func TestReadWasmConfig(t *testing.T) { + defaults := DefaultWasmConfig() + specs := map[string]struct { + src AppOptionsMock + exp types.WasmConfig + }{ + "set query gas limit via opts": { + src: AppOptionsMock{ + "wasm.query_gas_limit": 1, + }, + exp: types.WasmConfig{ + SmartQueryGasLimit: 1, + MemoryCacheSize: defaults.MemoryCacheSize, + }, + }, + "set cache via opts": { + src: AppOptionsMock{ + "wasm.memory_cache_size": 2, + }, + exp: types.WasmConfig{ + MemoryCacheSize: 2, + SmartQueryGasLimit: defaults.SmartQueryGasLimit, + }, + }, + "set debug via opts": { + src: AppOptionsMock{ + "trace": true, + }, + exp: types.WasmConfig{ + SmartQueryGasLimit: defaults.SmartQueryGasLimit, + MemoryCacheSize: defaults.MemoryCacheSize, + ContractDebugMode: true, + }, + }, + "all defaults when no options set": { + exp: defaults, + }, + } + for msg, spec := range specs { + t.Run(msg, func(t *testing.T) { + got, err := ReadWasmConfig(spec.src) + require.NoError(t, err) + assert.Equal(t, spec.exp, got) + }) + } +} + +type AppOptionsMock map[string]interface{} + +func (a AppOptionsMock) Get(s string) interface{} { + return a[s] +} + type prettyEvent struct { Type string Attr []sdk.Attribute