Skip to content

Commit

Permalink
feat: add change from wasmd v0.33.0
Browse files Browse the repository at this point in the history
  • Loading branch information
hoank101 committed Dec 23, 2023
1 parent 2a27f9b commit 94cbfa7
Show file tree
Hide file tree
Showing 18 changed files with 645 additions and 63 deletions.
15 changes: 15 additions & 0 deletions app/wasm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package app

// AllCapabilities returns all capabilities available with the current wasmvm
// See https://github.com/CosmWasm/cosmwasm/blob/main/docs/CAPABILITIES-BUILT-IN.md
// This functionality is going to be moved upstream: https://github.com/CosmWasm/wasmvm/issues/425
func AllCapabilities() []string {
return []string{
"iterator",
"staking",
"stargate",
"cosmwasm_1_1",
"cosmwasm_1_2",
"cosmwasm_1_3",
}
}
9 changes: 6 additions & 3 deletions x/wasm/client/cli/gov_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ package cli

import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
wasmvm "github.com/CosmWasm/wasmvm"
"net/url"
"strconv"
"strings"
Expand Down Expand Up @@ -149,11 +149,14 @@ func parseVerificationFlags(gzippedWasm []byte, flags *flag.FlagSet) (string, st
// wasm is gzipped in parseStoreCodeArgs
// checksum generation will be decoupled here
// reference https://github.com/CosmWasm/wasmvm/issues/359
raw, err := ioutils.Uncompress(gzippedWasm, uint64(types.MaxWasmSize))
raw, err := ioutils.Uncompress(gzippedWasm, int64(types.MaxWasmSize))
if err != nil {
return "", "", nil, fmt.Errorf("invalid zip: %w", err)
}
checksum := sha256.Sum256(raw)
checksum, err := wasmvm.CreateChecksum(raw)
if err != nil {
return "", "", nil, fmt.Errorf("checksum: %s", err)
}
if !bytes.Equal(checksum[:], codeHash) {
return "", "", nil, fmt.Errorf("code-hash mismatch: %X, checksum: %X", codeHash, checksum)
}
Expand Down
11 changes: 8 additions & 3 deletions x/wasm/ioutils/ioutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package ioutils
import (
"bytes"
"compress/gzip"
errorsmod "cosmossdk.io/errors"
"io"

"github.com/CosmWasm/wasmd/x/wasm/types"
)

// Uncompress expects a valid gzip source to unpack or fails. See IsGzip
func Uncompress(gzipSrc []byte, limit uint64) ([]byte, error) {
if uint64(len(gzipSrc)) > limit {
func Uncompress(gzipSrc []byte, limit int64) ([]byte, error) {
if int64(len(gzipSrc)) > limit {
return nil, types.ErrLimit
}
zr, err := gzip.NewReader(bytes.NewReader(gzipSrc))
Expand All @@ -19,7 +20,11 @@ func Uncompress(gzipSrc []byte, limit uint64) ([]byte, error) {
}
zr.Multistream(false)
defer zr.Close()
return io.ReadAll(LimitReader(zr, int64(limit)))
bz, err := io.ReadAll(LimitReader(zr, limit))
if types.ErrLimit.Is(err) {
return nil, errorsmod.Wrapf(err, "max %d bytes", limit)
}
return bz, err
}

// LimitReader returns a Reader that reads from r
Expand Down
10 changes: 10 additions & 0 deletions x/wasm/keeper/handler_plugin_encoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,16 @@ func EncodeDistributionMsg(sender sdk.AccAddress, msg *wasmvmtypes.DistributionM
ValidatorAddress: msg.WithdrawDelegatorReward.Validator,
}
return []sdk.Msg{&withdrawMsg}, nil
case msg.FundCommunityPool != nil:
amt, err := ConvertWasmCoinsToSdkCoins(msg.FundCommunityPool.Amount)
if err != nil {
return nil, err
}
fundMsg := distributiontypes.MsgFundCommunityPool{
Depositor: sender.String(),
Amount: amt,
}
return []sdk.Msg{&fundMsg}, nil
default:
return nil, errorsmod.Wrap(types.ErrUnknownMsg, "unknown variant of Distribution")
}
Expand Down
22 changes: 22 additions & 0 deletions x/wasm/keeper/handler_plugin_encoders_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,28 @@ func TestEncoding(t *testing.T) {
},
},
},
"distribution fund community pool": {
sender: addr1,
srcMsg: wasmvmtypes.CosmosMsg{
Distribution: &wasmvmtypes.DistributionMsg{
FundCommunityPool: &wasmvmtypes.FundCommunityPoolMsg{
Amount: wasmvmtypes.Coins{
wasmvmtypes.NewCoin(200, "stones"),
wasmvmtypes.NewCoin(200, "feathers"),
},
},
},
},
output: []sdk.Msg{
&distributiontypes.MsgFundCommunityPool{
Depositor: addr1.String(),
Amount: sdk.NewCoins(
sdk.NewInt64Coin("stones", 200),
sdk.NewInt64Coin("feathers", 200),
),
},
},
},
"stargate encoded bank msg": {
sender: addr2,
srcMsg: wasmvmtypes.CosmosMsg{
Expand Down
4 changes: 2 additions & 2 deletions x/wasm/keeper/keeper.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ func (k Keeper) create(ctx sdk.Context, creator sdk.AccAddress, wasmCode []byte,

if ioutils.IsGzip(wasmCode) {
ctx.GasMeter().ConsumeGas(k.gasRegister.UncompressCosts(len(wasmCode)), "Uncompress gzip bytecode")
wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize))
wasmCode, err = ioutils.Uncompress(wasmCode, int64(types.MaxWasmSize))
if err != nil {
return 0, checksum, errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
Expand Down Expand Up @@ -191,7 +191,7 @@ func (k Keeper) storeCodeInfo(ctx sdk.Context, codeID uint64, codeInfo types.Cod
func (k Keeper) importCode(ctx sdk.Context, codeID uint64, codeInfo types.CodeInfo, wasmCode []byte) error {
if ioutils.IsGzip(wasmCode) {
var err error
wasmCode, err = ioutils.Uncompress(wasmCode, uint64(types.MaxWasmSize))
wasmCode, err = ioutils.Uncompress(wasmCode, int64(types.MaxWasmSize))
if err != nil {
return errorsmod.Wrap(types.ErrCreateFailed, err.Error())
}
Expand Down
7 changes: 7 additions & 0 deletions x/wasm/keeper/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ func WithWasmEngine(x types.WasmerEngine) Option {
})
}

// WithWasmEngineDecorator is an optional constructor parameter to decorate the default wasmVM engine.
func WithWasmEngineDecorator(d func(old types.WasmerEngine) types.WasmerEngine) Option {
return optsFn(func(k *Keeper) {
k.wasmVM = d(k.wasmVM)
})
}

// WithMessageHandler is an optional constructor parameter to set a custom handler for wasmVM messages.
// This option should not be combined with Option `WithMessageEncoders` or `WithMessageHandlerDecorator`
func WithMessageHandler(x Messenger) Option {
Expand Down
10 changes: 10 additions & 0 deletions x/wasm/keeper/options_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package keeper

import (
wasmvm "github.com/CosmWasm/wasmvm"
"reflect"
"testing"

Expand Down Expand Up @@ -29,6 +30,15 @@ func TestConstructorOptions(t *testing.T) {
assert.IsType(t, &wasmtesting.MockWasmer{}, k.wasmVM)
},
},
"decorate wasmvm": {
srcOpt: WithWasmEngineDecorator(func(old types.WasmerEngine) types.WasmerEngine {
require.IsType(t, &wasmvm.VM{}, old)
return &wasmtesting.MockWasmer{}
}),
verify: func(t *testing.T, k Keeper) {
assert.IsType(t, &wasmtesting.MockWasmer{}, k.wasmVM)
},
},
"message handler": {
srcOpt: WithMessageHandler(&wasmtesting.MockMessageHandler{}),
verify: func(t *testing.T, k Keeper) {
Expand Down
116 changes: 103 additions & 13 deletions x/wasm/keeper/query_plugins.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package keeper
import (
"encoding/json"
"errors"
"github.com/cosmos/cosmos-sdk/types/query"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"

errorsmod "cosmossdk.io/errors"
"github.com/cosmos/cosmos-sdk/baseapp"
Expand Down Expand Up @@ -77,12 +79,13 @@ 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 *wasmvmtypes.BankQuery) ([]byte, error)
Custom CustomQuerier
IBC func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error)
Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error)
Stargate func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error)
Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error)
Bank func(ctx sdk.Context, request *wasmvmtypes.BankQuery) ([]byte, error)
Custom CustomQuerier
IBC func(ctx sdk.Context, caller sdk.AccAddress, request *wasmvmtypes.IBCQuery) ([]byte, error)
Staking func(ctx sdk.Context, request *wasmvmtypes.StakingQuery) ([]byte, error)
Stargate func(ctx sdk.Context, request *wasmvmtypes.StargateQuery) ([]byte, error)
Wasm func(ctx sdk.Context, request *wasmvmtypes.WasmQuery) ([]byte, error)
Distribution func(ctx sdk.Context, request *wasmvmtypes.DistributionQuery) ([]byte, error)
}

type contractMetaDataSource interface {
Expand All @@ -105,12 +108,13 @@ func DefaultQueryPlugins(
wasm wasmQueryKeeper,
) QueryPlugins {
return QueryPlugins{
Bank: BankQuerier(bank),
Custom: NoCustomQuerier,
IBC: IBCQuerier(wasm, channelKeeper),
Staking: StakingQuerier(staking, distKeeper),
Stargate: StargateQuerier(),
Wasm: WasmQuerier(wasm),
Bank: BankQuerier(bank),
Custom: NoCustomQuerier,
IBC: IBCQuerier(wasm, channelKeeper),
Staking: StakingQuerier(staking, distKeeper),
Stargate: StargateQuerier(),
Wasm: WasmQuerier(wasm),
Distribution: DistributionQuerier(distKeeper),
}
}

Expand All @@ -137,6 +141,9 @@ func (e QueryPlugins) Merge(o *QueryPlugins) QueryPlugins {
if o.Wasm != nil {
e.Wasm = o.Wasm
}
if o.Distribution != nil {
e.Distribution = o.Distribution
}
return e
}

Expand All @@ -161,6 +168,9 @@ func (e QueryPlugins) HandleQuery(ctx sdk.Context, caller sdk.AccAddress, reques
if request.Wasm != nil {
return e.Wasm(ctx, request.Wasm)
}
if request.Distribution != nil {
return e.Distribution(ctx, request.Distribution)
}
return nil, wasmvmtypes.Unknown{}
}

Expand Down Expand Up @@ -201,6 +211,27 @@ func BankQuerier(bankKeeper types.BankViewKeeper) func(ctx sdk.Context, request
}
return json.Marshal(res)
}
if request.DenomMetadata != nil {
denomMetadata, ok := bankKeeper.GetDenomMetaData(ctx, request.DenomMetadata.Denom)
if !ok {
return nil, sdkerrors.Wrap(sdkerrors.ErrNotFound, request.DenomMetadata.Denom)
}
res := wasmvmtypes.DenomMetadataResponse{
Metadata: ConvertSdkDenomMetadataToWasmDenomMetadata(denomMetadata),
}
return json.Marshal(res)
}
if request.AllDenomMetadata != nil {
bankQueryRes, err := bankKeeper.DenomsMetadata(ctx, ConvertToDenomsMetadataRequest(request.AllDenomMetadata))
if err != nil {
return nil, sdkerrors.ErrInvalidRequest
}
res := wasmvmtypes.AllDenomMetadataResponse{
Metadata: ConvertSdkDenomMetadatasToWasmDenomMetadatas(bankQueryRes.Metadatas),
NextKey: bankQueryRes.Pagination.NextKey,
}
return json.Marshal(res)
}
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown BankQuery variant"}
}
}
Expand Down Expand Up @@ -454,7 +485,7 @@ func getAccumulatedRewards(ctx sdk.Context, distKeeper types.DistributionKeeper,
ValidatorAddress: delegation.ValidatorAddress,
}
cache, _ := ctx.CacheContext()
qres, err := distKeeper.DelegationRewards(sdk.WrapSDKContext(cache), &params)
qres, err := distKeeper.DelegationRewards(cache, &params)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -529,6 +560,22 @@ func WasmQuerier(k wasmQueryKeeper) func(ctx sdk.Context, request *wasmvmtypes.W
}
}

func DistributionQuerier(k types.DistributionKeeper) func(ctx sdk.Context, request *wasmvmtypes.DistributionQuery) ([]byte, error) {
return func(ctx sdk.Context, req *wasmvmtypes.DistributionQuery) ([]byte, error) {
if req.DelegatorWithdrawAddress == nil {
return nil, wasmvmtypes.UnsupportedRequest{Kind: "unknown distribution query"}
}
addr, err := sdk.AccAddressFromBech32(req.DelegatorWithdrawAddress.DelegatorAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrap("delegator address")
}
res := wasmvmtypes.DelegatorWithdrawAddressResponse{
WithdrawAddress: k.GetDelegatorWithdrawAddr(ctx, addr).String(),
}
return json.Marshal(res)
}
}

// ConvertSdkCoinsToWasmCoins covert sdk type to wasmvm coins type
func ConvertSdkCoinsToWasmCoins(coins []sdk.Coin) wasmvmtypes.Coins {
converted := make(wasmvmtypes.Coins, len(coins))
Expand All @@ -546,6 +593,49 @@ func ConvertSdkCoinToWasmCoin(coin sdk.Coin) wasmvmtypes.Coin {
}
}

func ConvertToDenomsMetadataRequest(wasmRequest *wasmvmtypes.AllDenomMetadataQuery) *banktypes.QueryDenomsMetadataRequest {
ret := &banktypes.QueryDenomsMetadataRequest{}
if wasmRequest.Pagination != nil {
ret.Pagination = &query.PageRequest{
Key: wasmRequest.Pagination.Key,
Limit: uint64(wasmRequest.Pagination.Limit),
Reverse: wasmRequest.Pagination.Reverse,
}
}
return ret
}

func ConvertSdkDenomMetadatasToWasmDenomMetadatas(metadata []banktypes.Metadata) []wasmvmtypes.DenomMetadata {
converted := make([]wasmvmtypes.DenomMetadata, len(metadata))
for i, m := range metadata {
converted[i] = ConvertSdkDenomMetadataToWasmDenomMetadata(m)
}
return converted
}

func ConvertSdkDenomMetadataToWasmDenomMetadata(metadata banktypes.Metadata) wasmvmtypes.DenomMetadata {
return wasmvmtypes.DenomMetadata{
Description: metadata.Description,
DenomUnits: ConvertSdkDenomUnitsToWasmDenomUnits(metadata.DenomUnits),
Base: metadata.Base,
Display: metadata.Display,
Name: metadata.Name,
Symbol: metadata.Symbol,
}
}

func ConvertSdkDenomUnitsToWasmDenomUnits(denomUnits []*banktypes.DenomUnit) []wasmvmtypes.DenomUnit {
converted := make([]wasmvmtypes.DenomUnit, len(denomUnits))
for i, u := range denomUnits {
converted[i] = wasmvmtypes.DenomUnit{
Denom: u.Denom,
Exponent: u.Exponent,
Aliases: u.Aliases,
}
}
return converted
}

// ConvertProtoToJSONMarshal unmarshals the given bytes into a proto message and then marshals it to json.
// This is done so that clients calling stargate queries do not need to define their own proto unmarshalers,
// being able to use response directly by json marshalling, which is supported in cosmwasm.
Expand Down
Loading

0 comments on commit 94cbfa7

Please sign in to comment.