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

test(08-wasm): added 'TestUpdateState' using mockVM #4914

Merged
merged 19 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions modules/light-clients/08-wasm/types/export_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,8 @@ type (
TimestampAtHeightResult = timestampAtHeightResult
CheckForMisbehaviourResult = checkForMisbehaviourResult
UpdateStateResult = updateStateResult

// CallbackFn types
QueryFn = queryFn
SudoFn = sudoFn
)
304 changes: 116 additions & 188 deletions modules/light-clients/08-wasm/types/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,20 @@ package types_test

import (
"encoding/base64"
"encoding/json"
"fmt"

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

errorsmod "cosmossdk.io/errors"

wasmtesting "github.com/cosmos/ibc-go/modules/light-clients/08-wasm/testing"
"github.com/cosmos/ibc-go/modules/light-clients/08-wasm/types"
clienttypes "github.com/cosmos/ibc-go/v8/modules/core/02-client/types"
host "github.com/cosmos/ibc-go/v8/modules/core/24-host"
"github.com/cosmos/ibc-go/v8/modules/core/exported"
tmtypes "github.com/cosmos/ibc-go/v8/modules/light-clients/07-tendermint"
)

func (suite *TypesTestSuite) TestVerifyHeaderGrandpa() {
Expand Down Expand Up @@ -449,208 +458,127 @@ func (suite *TypesTestSuite) TestUpdateStateGrandpa() {
}
}

// func (suite *TypesTestSuite) TestUpdateStateTendermint() {
// var (
// path *ibctesting.Path
// clientMessage exported.ClientMessage
// clientStore sdk.KVStore
// consensusHeights []exported.Height
// pruneHeight clienttypes.Height
// prevClientState exported.ClientState
// prevConsensusState exported.ConsensusState
// )

// testCases := []struct {
// name string
// malleate func()
// expResult func()
// expPass bool
// }{
// {
// "success with height later than latest height", func() {
// suite.Require().True(path.EndpointA.GetClientState().GetLatestHeight().LT(height))
// },
// func() {
// clientState := path.EndpointA.GetClientState()
// suite.Require().True(clientState.GetLatestHeight().EQ(height)) // new update, updated client state should have changed
// suite.Require().True(clientState.GetLatestHeight().EQ(consensusHeights[0]))
// }, true,
// },
// {
// "success with height earlier than latest height", func() {
// // commit a block so the pre-created ClientMessage
// // isn't used to update the client to a newer height
// suite.coordinator.CommitBlock(suite.chainB)
// err := path.EndpointA.UpdateClient()
// suite.Require().NoError(err)

// suite.Require().True(path.EndpointA.GetClientState().GetLatestHeight().GT(height))

// prevClientState = path.EndpointA.GetClientState()
// },
// func() {
// clientState := path.EndpointA.GetClientState()
// suite.Require().Equal(clientState, prevClientState) // fill in height, no change to client state
// suite.Require().True(clientState.GetLatestHeight().GT(consensusHeights[0]))
// }, true,
// },
// {
// "success with duplicate header", func() {
// // update client in advance
// err := path.EndpointA.UpdateClient()
// suite.Require().NoError(err)

// // use the same header which just updated the client
// clientMessage, height, err = path.EndpointA.Chain.ConstructUpdateWasmClientHeader(path.EndpointA.Counterparty.Chain, path.EndpointA.ClientID)
// suite.Require().NoError(err)
// suite.Require().Equal(path.EndpointA.GetClientState().GetLatestHeight(), height)

// prevClientState = path.EndpointA.GetClientState()
// prevConsensusState = path.EndpointA.GetConsensusState(height)
// },
// func() {
// clientState := path.EndpointA.GetClientState()
// suite.Require().Equal(clientState, prevClientState)
// suite.Require().True(clientState.GetLatestHeight().EQ(consensusHeights[0]))
// suite.Require().Equal(path.EndpointA.GetConsensusState(height), prevConsensusState)
// }, true,
// },
// {
// "success with pruned consensus state", func() {
// // this height will be expired and pruned
// err := path.EndpointA.UpdateClient()
// suite.Require().NoError(err)
// pruneHeight = path.EndpointA.GetClientState().GetLatestHeight().(clienttypes.Height)

// // Increment the time by a week
// suite.coordinator.IncrementTimeBy(7 * 24 * time.Hour)

// // create the consensus state that can be used as trusted height for next update
// err = path.EndpointA.UpdateClient()
// suite.Require().NoError(err)

// // Increment the time by another week, then update the client.
// // This will cause the first two consensus states to become expired.
// suite.coordinator.IncrementTimeBy(7 * 24 * time.Hour)
// err = path.EndpointA.UpdateClient()
// suite.Require().NoError(err)

// // ensure counterparty state is committed
// suite.coordinator.CommitBlock(suite.chainB)
// clientMessage, height, err = path.EndpointA.Chain.ConstructUpdateWasmClientHeader(path.EndpointA.Counterparty.Chain, path.EndpointA.ClientID)
// suite.Require().NoError(err)
// },
// func() {
// clientState := path.EndpointA.GetClientState()
// suite.Require().True(clientState.GetLatestHeight().EQ(height)) // new update, updated client state should have changed
// suite.Require().True(clientState.GetLatestHeight().EQ(consensusHeights[0]))

// // ensure consensus state was pruned
// _, found := path.EndpointA.Chain.GetConsensusState(path.EndpointA.ClientID, pruneHeight)
// suite.Require().False(found)
// }, true,
// },
// {
// "success with pruned consensus state using duplicate header", func() {
// // this height will be expired and pruned
// err := path.EndpointA.UpdateClient()
// suite.Require().NoError(err)
// pruneHeight = path.EndpointA.GetClientState().GetLatestHeight().(clienttypes.Height)
func (suite *TypesTestSuite) TestUpdateState() {
errMsg := fmt.Errorf("callbackFn error")
srdtrk marked this conversation as resolved.
Show resolved Hide resolved
mockClientStateBz := []byte("mockClientStateBz")
charleenfei marked this conversation as resolved.
Show resolved Hide resolved
mockHeight := clienttypes.NewHeight(1, 1)

// // assert that a consensus state exists at the prune height
// consensusState, found := path.EndpointA.Chain.GetConsensusState(path.EndpointA.ClientID, pruneHeight)
// suite.Require().True(found)
// suite.Require().NotNil(consensusState)

// // Increment the time by a week
// suite.coordinator.IncrementTimeBy(7 * 24 * time.Hour)
var (
callbackFn types.SudoFn
clientMsg exported.ClientMessage
)

// // create the consensus state that can be used as trusted height for next update
// err = path.EndpointA.UpdateClient()
// suite.Require().NoError(err)
testCases := []struct {
name string
malleate func()
expPanic error
expHeights []exported.Height
expClientState []byte
}{
{
"success: no update",
func() {},
nil,
[]exported.Height{},
nil,
},
{
"success: update client",
func() {
callbackFn = func(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ []byte, store wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) {
srdtrk marked this conversation as resolved.
Show resolved Hide resolved
srdtrk marked this conversation as resolved.
Show resolved Hide resolved
store.Set(host.ClientStateKey(), mockClientStateBz)
srdtrk marked this conversation as resolved.
Show resolved Hide resolved
updateStateResp := types.UpdateStateResult{
Heights: []clienttypes.Height{mockHeight},
}

resp, err := json.Marshal(updateStateResp)
if err != nil {
return nil, 0, err
}

return &wasmvmtypes.Response{
Data: resp,
}, types.DefaultGasUsed, nil
}
},
nil,
[]exported.Height{mockHeight},
mockClientStateBz,
},
{
"failure: invalid ClientMessage type",
func() {
clientMsg = &tmtypes.Misbehaviour{}
},
fmt.Errorf("expected type %T, got %T", (*types.ClientMessage)(nil), (*tmtypes.Misbehaviour)(nil)),
nil,
nil,
},
{
"failure: callbackFn returns error",
func() {
callbackFn = func(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) {
return nil, 0, errMsg
}
},
errorsmod.Wrapf(errMsg, "call to wasm contract failed"),
nil,
nil,
},
}

// // Increment the time by another week, then update the client.
// // This will cause the first two consensus states to become expired.
// suite.coordinator.IncrementTimeBy(7 * 24 * time.Hour)
// err = path.EndpointA.UpdateClient()
// suite.Require().NoError(err)
for _, tc := range testCases {
suite.Run(tc.name, func() {
suite.SetupWasmWithMockVM() // reset

// // use the same header which just updated the client
// clientMessage, height, err = path.EndpointA.Chain.ConstructUpdateWasmClientHeader(path.EndpointA.Counterparty.Chain, path.EndpointA.ClientID)
// suite.Require().NoError(err)
// },
// func() {
// clientState := path.EndpointA.GetClientState()
// suite.Require().True(clientState.GetLatestHeight().EQ(height)) // new update, updated client state should have changed
// suite.Require().True(clientState.GetLatestHeight().EQ(consensusHeights[0]))

// // ensure consensus state was pruned
// _, found := path.EndpointA.Chain.GetConsensusState(path.EndpointA.ClientID, pruneHeight)
// suite.Require().False(found)
// }, true,
// },
// {
// "invalid ClientMessage type", func() {
// clientMessage = &ibctm.Misbehaviour{}
// },
// func() {},
// false,
// },
// }
// for _, tc := range testCases {
// suite.Run(tc.name, func() {
// suite.SetupWasmTendermint() // reset
// path = ibctesting.NewPath(suite.chainA, suite.chainB)
callbackFn = func(_ wasmvm.Checksum, _ wasmvmtypes.Env, _ []byte, _ wasmvm.KVStore, _ wasmvm.GoAPI, _ wasmvm.Querier, _ wasmvm.GasMeter, _ uint64, _ wasmvmtypes.UFraction) (*wasmvmtypes.Response, uint64, error) {
updateStateResp := types.UpdateStateResult{
Heights: []clienttypes.Height{},
}

// err := path.EndpointA.CreateClient()
// suite.Require().NoError(err)
resp, err := json.Marshal(updateStateResp)
if err != nil {
return nil, 0, err
}

// // ensure counterparty state is committed
// suite.coordinator.CommitBlock(suite.chainB)
// clientMessage, height, err = path.EndpointA.Chain.ConstructUpdateWasmClientHeader(path.EndpointA.Counterparty.Chain, path.EndpointA.ClientID)
// suite.Require().NoError(err)
return &wasmvmtypes.Response{
Data: resp,
}, types.DefaultGasUsed, nil
}

// tc.malleate()
clientMsg = &types.ClientMessage{
Data: []byte{1},
}

// clientState := path.EndpointA.GetClientState()
// clientStore = suite.chainA.App.GetIBCKeeper().ClientKeeper.ClientStore(suite.chainA.GetContext(), path.EndpointA.ClientID)
endpoint := wasmtesting.NewWasmEndpoint(suite.chainA)
err := endpoint.CreateClient()
suite.Require().NoError(err)

// if tc.expPass {
// consensusHeights = clientState.UpdateState(suite.chainA.GetContext(), suite.chainA.App.AppCodec(), clientStore, clientMessage)
tc.malleate()

// clientMessage, ok := clientMessage.(*types.ClientMessage)
// suite.Require().True(ok)
// var eHeader exported.ClientMessage
// err := suite.chainA.Codec.UnmarshalInterface(clientMessage.Data, &eHeader)
// tmHeader := eHeader.(*ibctm.Header)
// suite.Require().NoError(err)
// expTmConsensusState := &ibctm.ConsensusState{
// Timestamp: tmHeader.GetTime(),
// Root: commitmenttypes.NewMerkleRoot(tmHeader.Header.GetAppHash()),
// NextValidatorsHash: tmHeader.Header.NextValidatorsHash,
// }
// wasmData, err := suite.chainA.Codec.MarshalInterface(expTmConsensusState)
// suite.Require().NoError(err)
// expWasmConsensusState := &types.ConsensusState{
// Data: wasmData,
// }
suite.mockVM.RegisterSudoCallback(types.UpdateStateMsg{}, callbackFn)

// bz := clientStore.Get(host.ConsensusStateKey(height))
// updatedConsensusState := clienttypes.MustUnmarshalConsensusState(suite.chainA.App.AppCodec(), bz)
clientState := endpoint.GetClientState()

// suite.Require().Equal(expWasmConsensusState, updatedConsensusState)
var heights []exported.Height
charleenfei marked this conversation as resolved.
Show resolved Hide resolved
updateState := func() {
heights = clientState.UpdateState(suite.ctx, suite.chainA.Codec, suite.store, clientMsg)
}

// } else {
// suite.Require().Panics(func() {
// clientState.UpdateState(suite.chainA.GetContext(), suite.chainA.App.AppCodec(), clientStore, clientMessage)
// })
// }
if tc.expPanic == nil {
updateState()
suite.Require().Equal(tc.expHeights, heights)

// // perform custom checks
// tc.expResult()
// })
// }
// }
if tc.expClientState != nil {
clientStateBz := suite.store.Get(host.ClientStateKey())
suite.Require().Equal(tc.expClientState, clientStateBz)
}
} else {
suite.Require().PanicsWithError(tc.expPanic.Error(), updateState)
}
})
}
}

/* func (suite *TypesTestSuite) TestUpdateStateOnMisbehaviourGrandpa() {
var (
Expand Down
Loading