Skip to content

Commit

Permalink
merge main and fix config
Browse files Browse the repository at this point in the history
  • Loading branch information
DongLieu committed Oct 23, 2023
2 parents d6be692 + 922fcb1 commit 0180b82
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 25 deletions.
54 changes: 32 additions & 22 deletions x/interchainstaking/keeper/abci.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,29 +48,39 @@ func (k *Keeper) BeginBlocker(ctx sdk.Context) {
}

connection, found := k.IBCKeeper.ConnectionKeeper.GetConnection(ctx, zone.ConnectionId)
if found {
consState, found := k.IBCKeeper.ClientKeeper.GetLatestClientConsensusState(ctx, connection.GetClientID())
if found {
tmConsState, ok := consState.(*tmtypes.ConsensusState)
if ok {
if len(zone.IbcNextValidatorsHash) == 0 || !bytes.Equal(zone.IbcNextValidatorsHash, tmConsState.NextValidatorsHash.Bytes()) {
k.Logger(ctx).Info("IBC ValSet has changed; requerying valset")
// trigger valset update.
period := int64(k.GetParam(ctx, types.KeyValidatorSetInterval))
query := stakingTypes.QueryValidatorsRequest{}
err := k.EmitValSetQuery(ctx, zone.ConnectionId, zone.ChainId, query, sdkmath.NewInt(period))
if err != nil {
k.Logger(ctx).Error("unable to trigger valset update query", "error", err.Error())
// failing to emit the valset update is not terminal but constitutes
// an error, as if this starts happening frequent it is something
// we should investigate.
}
zone.IbcNextValidatorsHash = tmConsState.NextValidatorsHash.Bytes()
k.SetZone(ctx, zone)
}
}
}
if !found {
return false
}

consState, found := k.IBCKeeper.ClientKeeper.GetLatestClientConsensusState(ctx, connection.GetClientID())
if !found {
return false
}

tmConsState, ok := consState.(*tmtypes.ConsensusState)
if !ok {
return false
}

changedValSet := len(zone.IbcNextValidatorsHash) == 0 || !bytes.Equal(zone.IbcNextValidatorsHash, tmConsState.NextValidatorsHash.Bytes())
if !changedValSet {
return false
}

k.Logger(ctx).Info("IBC ValSet has changed; requerying valset")
// trigger valset update.
period := int64(k.GetParam(ctx, types.KeyValidatorSetInterval))
query := stakingTypes.QueryValidatorsRequest{}
err := k.EmitValSetQuery(ctx, zone.ConnectionId, zone.ChainId, query, sdkmath.NewInt(period))
if err != nil {
k.Logger(ctx).Error("unable to trigger valset update query", "error", err.Error())
// failing to emit the valset update is not terminal but constitutes
// an error, as if this starts happening frequent it is something
// we should investigate.
}

zone.IbcNextValidatorsHash = tmConsState.NextValidatorsHash.Bytes()
k.SetZone(ctx, zone)
return false
})
}
3 changes: 2 additions & 1 deletion x/interchainstaking/keeper/address_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ func (k Keeper) IterateUserMappedAccounts(ctx sdk.Context, localAddress []byte,
defer iterator.Close()

i := int64(0)
remoteAddrPrefixLen := len(types.GetRemoteAddressPrefix(localAddress))
for ; iterator.Valid(); iterator.Next() {
value := iterator.Value()
key := iterator.Key()
chainIDBytes := key[len(types.GetRemoteAddressPrefix(localAddress)):]
chainIDBytes := key[remoteAddrPrefixLen:]
stop := fn(i, string(chainIDBytes), value)
if stop {
break
Expand Down
118 changes: 118 additions & 0 deletions x/interchainstaking/keeper/callbacks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ package keeper_test
import (
"bytes"
"encoding/base64"
"fmt"
"testing"
"time"

ics23 "github.com/confio/ics23/go"
"github.com/stretchr/testify/require"

sdk "github.com/cosmos/cosmos-sdk/types"
Expand All @@ -16,6 +18,8 @@ import (
distrtypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"

lightclienttypes "github.com/cosmos/ibc-go/v5/modules/light-clients/07-tendermint/types"

"github.com/quicksilver-zone/quicksilver/app"
"github.com/quicksilver-zone/quicksilver/utils/addressutils"
icqtypes "github.com/quicksilver-zone/quicksilver/x/interchainquery/types"
Expand Down Expand Up @@ -1607,6 +1611,120 @@ func (suite *KeeperTestSuite) TestDelegationAccountBalanceCallback() {
})
}

func decodeBase64NoErr(str string) []byte {
decoded, err := base64.StdEncoding.DecodeString(str)
if err != nil {
fmt.Println("Error decoding: ", str)
panic(err)
}
return decoded
}

func (suite *KeeperTestSuite) TestDepositTxCallback() {
setupIbc := func() (*app.Quicksilver, sdk.Context) {
// reset test suite
suite.SetupTest()
suite.setupTestZones()

// setup quicksilver test app
quicksilver := suite.GetQuicksilverApp(suite.chainA)
quicksilver.InterchainstakingKeeper.CallbackHandler().RegisterCallbacks()

// get chainA context
ctx := suite.chainA.GetContext()

// get zone chainB context
zone, _ := quicksilver.InterchainstakingKeeper.GetZone(ctx, suite.chainB.ChainID)
zone.DepositAddress.IncrementBalanceWaitgroup()
zone.WithdrawalAddress.IncrementBalanceWaitgroup()
quicksilver.InterchainstakingKeeper.SetZone(ctx, &zone)

// get the tx from fixture
txWithProofBz := decodeBase64NoErr(localDepositTxFixture)
txRes := icqtypes.GetTxWithProofResponse{}
err := quicksilver.InterchainQueryKeeper.IBCKeeper.Codec().Unmarshal(txWithProofBz, &txRes)
suite.NoError(err)

// update payload header to ensure we can validate it.
txRes.Header.Header.Time = ctx.BlockTime()
// setup ClientConsensusState for checking Header validation
// Cheat, and set the client state and consensus state for 07-tendermint-0 to match the incoming header.
quicksilver.IBCKeeper.ClientKeeper.SetClientState(ctx, "07-tendermint-0", lightclienttypes.NewClientState("gaiatest-1", lightclienttypes.DefaultTrustLevel, time.Hour, time.Hour, time.Second*50, txRes.Header.TrustedHeight, []*ics23.ProofSpec{}, []string{}, false, false))
quicksilver.IBCKeeper.ClientKeeper.SetClientConsensusState(ctx, "07-tendermint-0", txRes.Header.TrustedHeight, txRes.Header.ConsensusState())

return quicksilver, ctx
}

testCases := []struct {
name string
txHash string
txWithProofbz []byte
chainID string
expectErr bool
}{
{
name: "Deposit transaction successful",
// txHash that come from DepositTxFixture
txHash: "b1f1852d322328f6b8d8cacd180df2b1cbbd3dd64536c9ecbf1c896a15f6217a",
txWithProofbz: decodeBase64NoErr(localDepositTxFixture),
chainID: suite.chainB.ChainID,
expectErr: false,
},
{
name: "Deposit transaction failed: txHash mismatch",
// txHash that come from DepositTxFixture
txHash: "2CC0F0C5106F30F5D26ABE8CB93F1EF0CCCE10754207C38B129D76ED3B7C75B2",
txWithProofbz: decodeBase64NoErr(localDepositTxFixture),
chainID: suite.chainB.ChainID,
expectErr: true,
},
{
name: "Deposit transaction failed: nil bytes",
txHash: "b1f1852d322328f6b8d8cacd180df2b1cbbd3dd64536c9ecbf1c896a15f6217a",
txWithProofbz: nil,
chainID: suite.chainB.ChainID,
expectErr: true,
},
{
name: "Deposit transaction failed: wrong bytes",
txHash: "b1f1852d322328f6b8d8cacd180df2b1cbbd3dd64536c9ecbf1c896a15f6217a",
txWithProofbz: []byte("testing"),
chainID: suite.chainB.ChainID,
expectErr: true,
},
{
name: "Deposit transaction failed: zone not registered",
txHash: "b1f1852d322328f6b8d8cacd180df2b1cbbd3dd64536c9ecbf1c896a15f6217a",
txWithProofbz: decodeBase64NoErr(localDepositTxFixture),
chainID: "superNova",
expectErr: true,
},
}

for _, tc := range testCases {
suite.Run(fmt.Sprintf("Case %s", tc.name), func() {
// setup quicksilver and counter chain context
qckApp, ctx := setupIbc()

// construct request data using txHash
requestData := tx.GetTxRequest{
Hash: tc.txHash,
}
resDataBz, _ := qckApp.AppCodec().Marshal(&requestData)

// initialize the callback
err := keeper.DepositTxCallback(qckApp.InterchainstakingKeeper, ctx, tc.txWithProofbz, icqtypes.Query{ChainId: tc.chainID, Request: resDataBz})
if tc.expectErr {
suite.Error(err)
} else {
suite.NoError(err)
}
})
}
}

var localDepositTxFixture = `GsEDCiCFDDobCzFK2Vf0BXcgdEycLSdJL8IP7PEVWKelDQeJ3xL2AgrXAQrUAQocL2Nvc21vcy5iYW5rLnYxYmV0YTEuTXNnU2VuZBKzAQotY29zbW9zMWEyemh0OHgyajBkcXZ1ZWpyOHB4cHU3ZHVlM3FtazQwbGdkeTNoEkFjb3Ntb3MxYXZ2ZWhmM25wdm42d2V5eHR2eXU3bWh3d3Zqcnl6dzY5ZzQzdHEwbmw4MHdxamdscjZoc2U1bWN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ikQApp2uWUJQ/zAtwTr5PRWlVS5/wFJYMGBSDNh5EEWY4FTclhTHLV2aMyyH5pfH6L0fr50CEn4KPQoUeQRs3t3nFppZq/OiJ+/f0AsW+twSIgogx4ew5LC25gOeUAdpun5LhBSfIBHUbK7Zjyzn8VRr1ZwYhCESPQoUeQRs3t3nFppZq/OiJ+/f0AsW+twSIgogx4ew5LC25gOeUAdpun5LhBSfIBHUbK7Zjyzn8VRr1ZwYhCEaBggBEKvdDiJ+Cj0KFHkEbN7d5xaaWavzoifv39ALFvrcEiIKIMeHsOSwtuYDnlAHabp+S4QUnyAR1Gyu2Y8s5/FUa9WcGIQhEj0KFHkEbN7d5xaaWavzoifv39ALFvrcEiIKIMeHsOSwtuYDnlAHabp+S4QUnyAR1Gyu2Y8s5/FUa9WcGIQh`

func (suite *KeeperTestSuite) TestPerfBalanceCallbackUpdate() {
suite.Run("perf balance", func() {
suite.SetupTest()
Expand Down
2 changes: 0 additions & 2 deletions x/interchainstaking/keeper/ibc_packet_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,12 +467,10 @@ func (k *Keeper) HandleWithdrawForUser(ctx sdk.Context, zone *types.Zone, msg *b

if len(dlist) > 0 {
newDist := make([]*types.Distribution, 0)
i := 0
for idx := range withdrawalRecord.Distribution {
if _, remove := dlist[idx]; !remove {
newDist = append(newDist, withdrawalRecord.Distribution[idx])
}
i++
}
k.Logger(ctx).Info("found matching withdrawal; awaiting additional messages")
withdrawalRecord.Distribution = newDist
Expand Down

0 comments on commit 0180b82

Please sign in to comment.