Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add custom queries to wasm module #5261

Merged
merged 11 commits into from
Dec 1, 2023
14 changes: 14 additions & 0 deletions modules/light-clients/08-wasm/internal/ibcwasm/wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,17 @@ package ibcwasm
import (
"errors"

wasmvm "github.com/CosmWasm/wasmvm"

"cosmossdk.io/collections"
storetypes "cosmossdk.io/core/store"
)

var (
vm WasmEngine

querier wasmvm.Querier

// state management
Schema collections.Schema
Checksums collections.KeySet[[]byte]
Expand All @@ -32,6 +36,16 @@ func GetVM() WasmEngine {
return vm
}

// SetQuerier sets the custom wasm query handle for the 08-wasm module.
func SetQuerier(wasmQuerier wasmvm.Querier) {
querier = wasmQuerier
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simon from Confio has warned us against nil queriers and they will not be allowed in the future, so it would be good to add a check here that wasmQuerier is not nil and also in NewKeeperWithVM, just as we do now for the vm.

Copy link
Contributor Author

@aeryz aeryz Nov 30, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense but also, isn't it a better API for end users to pass nil to NewKeeperWithVM and in the setter function, do:

if wasmQuerier == nil {
    querier = defaultQuerier // or noop or error, etc.
} 

This way we could hide the default type and users won't have to give that to the NewKeeperWithVM function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, basically this comment. Sorry lol: #5261 (comment)

}

// GetQuerier returns the custom wasm query handler for the 08-wasm module.
func GetQuerier() wasmvm.Querier {
return querier
damiannolan marked this conversation as resolved.
Show resolved Hide resolved
}

// SetupWasmStoreService sets up the 08-wasm module's collections.
func SetupWasmStoreService(storeService storetypes.KVStoreService) {
sb := collections.NewSchemaBuilder(storeService)
Expand Down
5 changes: 4 additions & 1 deletion modules/light-clients/08-wasm/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func NewKeeperWithVM(
clientKeeper types.ClientKeeper,
authority string,
vm ibcwasm.WasmEngine,
querier wasmvm.Querier,
) Keeper {
if clientKeeper == nil {
panic(errors.New("client keeper must be not nil"))
Expand All @@ -59,6 +60,7 @@ func NewKeeperWithVM(
}

ibcwasm.SetVM(vm)
ibcwasm.SetQuerier(querier)
ibcwasm.SetupWasmStoreService(storeService)

return Keeper{
Expand All @@ -77,13 +79,14 @@ func NewKeeperWithConfig(
clientKeeper types.ClientKeeper,
authority string,
wasmConfig types.WasmConfig,
querier wasmvm.Querier,
) Keeper {
vm, err := wasmvm.NewVM(wasmConfig.DataDir, wasmConfig.SupportedCapabilities, types.ContractMemoryLimit, wasmConfig.ContractDebugMode, types.MemoryCacheSize)
if err != nil {
panic(fmt.Errorf("failed to instantiate new Wasm VM instance: %v", err))
}

return NewKeeperWithVM(cdc, storeService, clientKeeper, authority, vm)
return NewKeeperWithVM(cdc, storeService, clientKeeper, authority, vm, querier)
}

// GetAuthority returns the 08-wasm module's authority.
Expand Down
5 changes: 5 additions & 0 deletions modules/light-clients/08-wasm/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() {
GetSimApp(suite.chainA).IBCKeeper.ClientKeeper,
GetSimApp(suite.chainA).WasmClientKeeper.GetAuthority(),
ibcwasm.GetVM(),
nil,
)
},
true,
Expand All @@ -170,6 +171,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() {
GetSimApp(suite.chainA).IBCKeeper.ClientKeeper,
"", // authority
ibcwasm.GetVM(),
nil,
)
},
false,
Expand All @@ -184,6 +186,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() {
nil, // client keeper,
GetSimApp(suite.chainA).WasmClientKeeper.GetAuthority(),
ibcwasm.GetVM(),
nil,
)
},
false,
Expand All @@ -198,6 +201,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() {
GetSimApp(suite.chainA).IBCKeeper.ClientKeeper,
GetSimApp(suite.chainA).WasmClientKeeper.GetAuthority(),
nil,
nil,
)
},
false,
Expand All @@ -212,6 +216,7 @@ func (suite *KeeperTestSuite) TestNewKeeper() {
GetSimApp(suite.chainA).IBCKeeper.ClientKeeper,
GetSimApp(suite.chainA).WasmClientKeeper.GetAuthority(),
ibcwasm.GetVM(),
nil,
)
},
false,
Expand Down
4 changes: 2 additions & 2 deletions modules/light-clients/08-wasm/testing/simapp/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,12 +471,12 @@ func NewSimApp(
// NOTE: mockVM is used for testing purposes only!
app.WasmClientKeeper = wasmkeeper.NewKeeperWithVM(
appCodec, runtime.NewKVStoreService(keys[wasmtypes.StoreKey]), app.IBCKeeper.ClientKeeper,
authtypes.NewModuleAddress(govtypes.ModuleName).String(), mockVM,
authtypes.NewModuleAddress(govtypes.ModuleName).String(), mockVM, nil,
)
} else {
app.WasmClientKeeper = wasmkeeper.NewKeeperWithConfig(
appCodec, runtime.NewKVStoreService(keys[wasmtypes.StoreKey]), app.IBCKeeper.ClientKeeper,
authtypes.NewModuleAddress(govtypes.ModuleName).String(), wasmConfig,
authtypes.NewModuleAddress(govtypes.ModuleName).String(), wasmConfig, nil,
)
}

Expand Down
98 changes: 98 additions & 0 deletions modules/light-clients/08-wasm/types/custom_query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package types_test

import (
"encoding/json"
"math"

wasmvm "github.com/CosmWasm/wasmvm"
wasmvmtypes "github.com/CosmWasm/wasmvm/types"

"github.com/cosmos/ibc-go/modules/light-clients/08-wasm/internal/ibcwasm"
wasmtesting "github.com/cosmos/ibc-go/modules/light-clients/08-wasm/testing"
"github.com/cosmos/ibc-go/modules/light-clients/08-wasm/types"
"github.com/cosmos/ibc-go/v8/modules/core/exported"
)

type CustomQuery struct {
Echo *QueryEcho `json:"echo,omitempty"`
}

type QueryEcho struct {
Data string `json:"data"`
}

type CustomQueryHandler struct{}

func (*CustomQueryHandler) GasConsumed() uint64 {
return 0
}

func (*CustomQueryHandler) Query(request wasmvmtypes.QueryRequest, gasLimit uint64) ([]byte, error) {
var customQuery CustomQuery
err := json.Unmarshal([]byte(request.Custom), &customQuery)
if err != nil {
return nil, wasmtesting.ErrMockContract
}

if customQuery.Echo != nil {
data, err := json.Marshal(customQuery.Echo.Data)
return data, err
}

return nil, wasmtesting.ErrMockContract
}

func (suite *TypesTestSuite) TestCustomQuery() {
testCases := []struct {
name string
malleate func()
}{
{
"success: custom query",
func() {
suite.mockVM.RegisterQueryCallback(types.StatusMsg{}, func(checksum wasmvm.Checksum, env wasmvmtypes.Env, queryMsg []byte, store wasmvm.KVStore, goapi wasmvm.GoAPI, querier wasmvm.Querier, gasMeter wasmvm.GasMeter, gasLimit uint64, deserCost wasmvmtypes.UFraction) ([]byte, uint64, error) {
echo := CustomQuery{
Echo: &QueryEcho{
Data: "hello world",
},
}
echoJSON, err := json.Marshal(echo)
suite.Require().NoError(err)

resp, err := querier.Query(wasmvmtypes.QueryRequest{
Custom: json.RawMessage(echoJSON),
}, math.MaxUint64)
suite.Require().NoError(err)

var respData string
err = json.Unmarshal(resp, &respData)
suite.Require().NoError(err)
suite.Require().Equal("hello world", respData)

resp, err = json.Marshal(types.StatusResult{Status: exported.Active.String()})
suite.Require().NoError(err)

return resp, wasmtesting.DefaultGasUsed, nil
})
},
},
}

for _, tc := range testCases {
suite.Run(tc.name, func() {
suite.SetupWasmWithMockVM()

endpoint := wasmtesting.NewWasmEndpoint(suite.chainA)
err := endpoint.CreateClient()
suite.Require().NoError(err)

tc.malleate()

clientStore := suite.chainA.App.GetIBCKeeper().ClientKeeper.ClientStore(suite.chainA.GetContext(), endpoint.ClientID)
clientState := endpoint.GetClientState()

ibcwasm.SetQuerier(&CustomQueryHandler{})
clientState.Status(suite.chainA.GetContext(), clientStore, suite.chainA.App.AppCodec())
})
}
}
8 changes: 4 additions & 4 deletions modules/light-clients/08-wasm/types/vm.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func instantiateContract(ctx sdk.Context, clientStore storetypes.KVStore, checks
}

ctx.GasMeter().ConsumeGas(VMGasRegister.NewContractInstanceCosts(true, len(msg)), "Loading CosmWasm module: instantiate")
response, gasUsed, err := ibcwasm.GetVM().Instantiate(checksum, env, msgInfo, msg, newStoreAdapter(clientStore), wasmvmAPI, nil, multipliedGasMeter, gasLimit, costJSONDeserialization)
response, gasUsed, err := ibcwasm.GetVM().Instantiate(checksum, env, msgInfo, msg, newStoreAdapter(clientStore), wasmvmAPI, ibcwasm.GetQuerier(), multipliedGasMeter, gasLimit, costJSONDeserialization)
VMGasRegister.consumeRuntimeGas(ctx, gasUsed)
return response, err
}
Expand All @@ -67,7 +67,7 @@ func callContract(ctx sdk.Context, clientStore storetypes.KVStore, checksum Chec
env := getEnv(ctx, clientID)

ctx.GasMeter().ConsumeGas(VMGasRegister.InstantiateContractCosts(true, len(msg)), "Loading CosmWasm module: sudo")
resp, gasUsed, err := ibcwasm.GetVM().Sudo(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, nil, multipliedGasMeter, gasLimit, costJSONDeserialization)
resp, gasUsed, err := ibcwasm.GetVM().Sudo(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, ibcwasm.GetQuerier(), multipliedGasMeter, gasLimit, costJSONDeserialization)
VMGasRegister.consumeRuntimeGas(ctx, gasUsed)
return resp, err
}
Expand All @@ -81,7 +81,7 @@ func migrateContract(ctx sdk.Context, clientID string, clientStore storetypes.KV
env := getEnv(ctx, clientID)

ctx.GasMeter().ConsumeGas(VMGasRegister.InstantiateContractCosts(true, len(msg)), "Loading CosmWasm module: migrate")
resp, gasUsed, err := ibcwasm.GetVM().Migrate(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, nil, multipliedGasMeter, gasLimit, costJSONDeserialization)
resp, gasUsed, err := ibcwasm.GetVM().Migrate(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, ibcwasm.GetQuerier(), multipliedGasMeter, gasLimit, costJSONDeserialization)
VMGasRegister.consumeRuntimeGas(ctx, gasUsed)
return resp, err
}
Expand All @@ -99,7 +99,7 @@ func queryContract(ctx sdk.Context, clientStore storetypes.KVStore, checksum Che
env := getEnv(ctx, clientID)

ctx.GasMeter().ConsumeGas(VMGasRegister.InstantiateContractCosts(true, len(msg)), "Loading CosmWasm module: query")
resp, gasUsed, err := ibcwasm.GetVM().Query(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, nil, multipliedGasMeter, gasLimit, costJSONDeserialization)
resp, gasUsed, err := ibcwasm.GetVM().Query(checksum, env, msg, newStoreAdapter(clientStore), wasmvmAPI, ibcwasm.GetQuerier(), multipliedGasMeter, gasLimit, costJSONDeserialization)
VMGasRegister.consumeRuntimeGas(ctx, gasUsed)
return resp, err
}
Expand Down
Loading