From 7cb083cc9eb840821b2dfbecbe2d3ac67169342b Mon Sep 17 00:00:00 2001 From: KyleMoser Date: Mon, 29 Jan 2024 18:31:28 -0500 Subject: [PATCH] External feegrants (#1338) * Allow feegrants where granter is external (relayer does not have key) * linting/logging * Added feegrant command gas flag * Added doc for external feegrant config * Fix logging to conform to style guide * Lock on read bech32 address map * Lock on read bech32 address map * Lock on read bech32 address map --------- Co-authored-by: Kyle --- cmd/feegrant.go | 71 ++-- docs/advanced_usage.md | 5 +- interchaintest/feegrant_test.go | 532 +++++++++++++++++++++++++++ interchaintest/go.mod | 5 + interchaintest/go.sum | 12 + relayer/chains/cosmos/bech32_hack.go | 11 +- relayer/chains/cosmos/codec.go | 24 +- relayer/chains/cosmos/feegrant.go | 217 +++++------ relayer/chains/cosmos/keys.go | 8 + relayer/chains/cosmos/provider.go | 16 +- relayer/chains/cosmos/tx.go | 41 ++- 11 files changed, 779 insertions(+), 163 deletions(-) diff --git a/cmd/feegrant.go b/cmd/feegrant.go index edb66d800..2d7055b4e 100644 --- a/cmd/feegrant.go +++ b/cmd/feegrant.go @@ -4,8 +4,11 @@ import ( "errors" "fmt" + sdkflags "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/relayer/v2/relayer/chains/cosmos" "github.com/spf13/cobra" + "go.uber.org/zap" ) // feegrantConfigureCmd returns the fee grant configuration commands for this module @@ -52,18 +55,27 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { if len(args) > 1 { granterKeyOrAddr = args[1] } else if prov.PCfg.FeeGrants != nil { - granterKeyOrAddr = prov.PCfg.FeeGrants.GranterKey + granterKeyOrAddr = prov.PCfg.FeeGrants.GranterKeyOrAddr } else { granterKeyOrAddr = prov.PCfg.Key } + externalGranter := false + granterKey, err := prov.KeyFromKeyOrAddress(granterKeyOrAddr) if err != nil { - return fmt.Errorf("could not get granter key from '%s'", granterKeyOrAddr) + externalGranter = true + } + + if externalGranter { + _, err := prov.DecodeBech32AccAddr(granterKeyOrAddr) + if err != nil { + return fmt.Errorf("an unknown granter was specified: '%s' is not a valid bech32 address", granterKeyOrAddr) + } } if delete { - fmt.Printf("Deleting %s feegrant configuration\n", chain) + a.log.Info("Deleting feegrant configuration", zap.String("chain", chain)) cfgErr := a.performConfigLockingOperation(cmd.Context(), func() error { chain := a.config.Chains[chain] @@ -75,11 +87,12 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { return nil } - if prov.PCfg.FeeGrants != nil && granterKey != prov.PCfg.FeeGrants.GranterKey && !update { - return fmt.Errorf("you specified granter '%s' which is different than configured feegranter '%s', but you did not specify the --overwrite-granter flag", granterKeyOrAddr, prov.PCfg.FeeGrants.GranterKey) - } else if prov.PCfg.FeeGrants != nil && granterKey != prov.PCfg.FeeGrants.GranterKey && update { + if prov.PCfg.FeeGrants != nil && granterKey != prov.PCfg.FeeGrants.GranterKeyOrAddr && !update { + return fmt.Errorf("you specified granter '%s' which is different than configured feegranter '%s', but you did not specify the --overwrite-granter flag", granterKeyOrAddr, prov.PCfg.FeeGrants.GranterKeyOrAddr) + } else if prov.PCfg.FeeGrants != nil && granterKey != prov.PCfg.FeeGrants.GranterKeyOrAddr && update { cfgErr := a.performConfigLockingOperation(cmd.Context(), func() error { - prov.PCfg.FeeGrants.GranterKey = granterKey + prov.PCfg.FeeGrants.GranterKeyOrAddr = granterKey + prov.PCfg.FeeGrants.IsExternalGranter = externalGranter return nil }) cobra.CheckErr(cfgErr) @@ -88,11 +101,16 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { if prov.PCfg.FeeGrants == nil || updateGrantees || len(grantees) > 0 { var feegrantErr error - //No list of grantees was provided, so we will use the default naming convention "grantee1, ... granteeN" + // No list of grantees was provided, so we will use the default naming convention "grantee1, ... granteeN" if grantees == nil { + if externalGranter { + return fmt.Errorf("external granter %s was specified, pre-authorized grantees must also be specified", granterKeyOrAddr) + } feegrantErr = prov.ConfigureFeegrants(numGrantees, granterKey) - } else { + } else if !externalGranter { feegrantErr = prov.ConfigureWithGrantees(grantees, granterKey) + } else { + feegrantErr = prov.ConfigureWithExternalGranter(grantees, granterKeyOrAddr) } if feegrantErr != nil { @@ -102,6 +120,7 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { cfgErr := a.performConfigLockingOperation(cmd.Context(), func() error { chain := a.config.Chains[chain] oldProv := chain.ChainProvider.(*cosmos.CosmosProvider) + prov.PCfg.FeeGrants.IsExternalGranter = externalGranter oldProv.PCfg.FeeGrants = prov.PCfg.FeeGrants return nil }) @@ -113,25 +132,32 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { return err } + gas := uint64(0) + gasStr, _ := cmd.Flags().GetString(sdkflags.FlagGas) + if gasStr != "" { + gasSetting, _ := sdkflags.ParseGasSetting(gasStr) + gas = gasSetting.Gas + } + ctx := cmd.Context() - _, err = prov.EnsureBasicGrants(ctx, memo) + _, err = prov.EnsureBasicGrants(ctx, memo, gas) if err != nil { return fmt.Errorf("error writing grants on chain: '%s'", err.Error()) } - //Get latest height from the chain, mark feegrant configuration as verified up to that height. - //This means we've verified feegranting is enabled on-chain and TXs can be sent with a feegranter. + // Get latest height from the chain, mark feegrant configuration as verified up to that height. + // This means we've verified feegranting is enabled on-chain and TXs can be sent with a feegranter. if prov.PCfg.FeeGrants != nil { - fmt.Printf("Querying latest chain height to mark FeeGrant height... \n") h, err := prov.QueryLatestHeight(ctx) cobra.CheckErr(err) cfgErr := a.performConfigLockingOperation(cmd.Context(), func() error { chain := a.config.Chains[chain] oldProv := chain.ChainProvider.(*cosmos.CosmosProvider) + prov.PCfg.FeeGrants.IsExternalGranter = externalGranter oldProv.PCfg.FeeGrants = prov.PCfg.FeeGrants oldProv.PCfg.FeeGrants.BlockHeightVerified = h - fmt.Printf("Feegrant chain height marked: %d\n", h) + a.log.Info("feegrant configured", zap.Int64("height", h)) return nil }) cobra.CheckErr(cfgErr) @@ -147,6 +173,7 @@ func feegrantConfigureBasicCmd(a *appState) *cobra.Command { cmd.Flags().IntVar(&numGrantees, "num-grantees", 10, "number of grantees that will be feegranted with basic allowances") cmd.Flags().StringSliceVar(&grantees, "grantees", nil, "comma separated list of grantee key names (keys are created if they do not exist)") cmd.MarkFlagsMutuallyExclusive("num-grantees", "grantees", "delete") + cmd.Flags().String(sdkflags.FlagGas, "", fmt.Sprintf("gas limit to set per-transaction; set to %q to calculate sufficient gas automatically (default %d)", sdkflags.GasFlagAuto, sdkflags.DefaultGasLimit)) memoFlag(a.viper, cmd) return cmd @@ -169,18 +196,6 @@ func feegrantBasicGrantsCmd(a *appState) *cobra.Command { return errors.New("only CosmosProvider can be feegranted") } - // TODO fix pagination - // pageReq, err := client.ReadPageRequest(cmd.Flags()) - // if err != nil { - // return err - // } - - //TODO fix height - // height, err := lensCmd.ReadHeight(cmd.Flags()) - // if err != nil { - // return err - // } - keyNameOrAddress := "" if len(args) == 0 { keyNameOrAddress = prov.PCfg.Key @@ -190,7 +205,7 @@ func feegrantBasicGrantsCmd(a *appState) *cobra.Command { granterAcc, err := prov.AccountFromKeyOrAddress(keyNameOrAddress) if err != nil { - fmt.Printf("Error retrieving account from key '%s'\n", keyNameOrAddress) + a.log.Error("Unknown account", zap.String("key_or_address", keyNameOrAddress), zap.Error(err)) return err } granterAddr := prov.MustEncodeAccAddr(granterAcc) @@ -203,7 +218,7 @@ func feegrantBasicGrantsCmd(a *appState) *cobra.Command { for _, grant := range res { allowance, e := prov.Sprint(grant.Allowance) cobra.CheckErr(e) - fmt.Printf("Granter: %s, Grantee: %s, Allowance: %s\n", grant.Granter, grant.Grantee, allowance) + a.log.Info("feegrant", zap.String("granter", grant.Granter), zap.String("grantee", grant.Grantee), zap.String("allowance", allowance)) } return nil diff --git a/docs/advanced_usage.md b/docs/advanced_usage.md index 996a694c1..83230db62 100644 --- a/docs/advanced_usage.md +++ b/docs/advanced_usage.md @@ -68,6 +68,10 @@ For example, configure feegrants for Kujira: - Note: above, `default` is the key that will need to contain funds (the granter) - 10 grantees will be configured, so those 10 address will sign TXs in round robin order. +An external feegrant configuration can be applied with the following command: +- `rly chains configure feegrant basicallowance cosmoshub cosmosaddr --grantees grantee3` +- Note: above, `cosmosaddr` is a bech32 address that has already issued a feegrant allowance to `grantee3`. +- External configuration means that someone else controls `cosmosaddr` (you do not need the mnemonic). You may also choose to specify the exact names of your grantees: - `rly chains configure feegrant basicallowance kujira default --grantees "kuji1,kuji2,kuji3"` @@ -78,7 +82,6 @@ Rerunning the feegrant command will simply confirm your configuration is correct To remove the feegrant configuration: - `rly chains configure feegrant basicallowance kujira --delete` - ## Stuck Packet There can be scenarios where a standard flush fails to clear a packet due to differences in the way packets are observed. The standard flush depends on the packet queries working properly. Sometimes the packet queries can miss things that the block scanning performed by the relayer during standard operation wouldn't. For packets affected by this, if they were emitted in recent blocks, the `--block-history` flag can be used to have the standard relayer block scanning start at a block height that many blocks behind the current chain tip. However, if the stuck packet occurred at an old height, farther back than would be reasonable for the `--block-history` scan from historical to current, there is an additional set of flags that can be used to zoom in on the block heights where the stuck packet occurred. diff --git a/interchaintest/feegrant_test.go b/interchaintest/feegrant_test.go index d04a74578..4e4b811cd 100644 --- a/interchaintest/feegrant_test.go +++ b/interchaintest/feegrant_test.go @@ -10,6 +10,7 @@ import ( "time" sdkmath "cosmossdk.io/math" + "cosmossdk.io/x/feegrant" "github.com/avast/retry-go/v4" "github.com/cosmos/cosmos-sdk/types" txtypes "github.com/cosmos/cosmos-sdk/types/tx" @@ -21,6 +22,7 @@ import ( "github.com/cosmos/relayer/v2/relayer/processor" clienttypes "github.com/strangelove-ventures/cometbft-client/client" "github.com/strangelove-ventures/interchaintest/v8" + cosmosv8 "github.com/strangelove-ventures/interchaintest/v8/chain/cosmos" "github.com/strangelove-ventures/interchaintest/v8/ibc" "github.com/strangelove-ventures/interchaintest/v8/testreporter" "github.com/strangelove-ventures/interchaintest/v8/testutil" @@ -547,3 +549,533 @@ func TxWithRetry(ctx context.Context, client *clienttypes.Client, hash []byte) ( return res, err } + +// TestRelayerFeeGrantExternal Feegrant on a single chain where the granter is an externally controlled address (no private key). +// Run this test with e.g. go test -timeout 300s -run ^TestRelayerFeeGrantExternal$ github.com/cosmos/relayer/v2/ibctest. +func TestRelayerFeeGrantExternal(t *testing.T) { + ctx := context.Background() + logger := zaptest.NewLogger(t) + + nv := 1 + nf := 0 + + var tests = [][]*interchaintest.ChainSpec{ + { + {Name: "gaia", ChainName: "gaia", Version: "v7.0.3", NumValidators: &nv, NumFullNodes: &nf}, + {Name: "osmosis", ChainName: "osmosis", Version: "v14.0.1", NumValidators: &nv, NumFullNodes: &nf}, + }, + { + {Name: "gaia", ChainName: "gaia", Version: "v7.0.3", NumValidators: &nv, NumFullNodes: &nf}, + {Name: "kujira", ChainName: "kujira", Version: "v0.8.7", NumValidators: &nv, NumFullNodes: &nf}, + }, + } + + for _, tt := range tests { + testname := fmt.Sprintf("%s,%s", tt[0].Name, tt[1].Name) + t.Run(testname, func(t *testing.T) { + + // Chain Factory + cf := interchaintest.NewBuiltinChainFactory(zaptest.NewLogger(t), tt) + + chains, err := cf.Chains(t.Name()) + require.NoError(t, err) + gaia, osmosis := chains[0], chains[1] + + // Relayer Factory to construct relayer + r := NewRelayerFactory(RelayerConfig{ + Processor: relayer.ProcessorEvents, + InitialBlockHistory: 100, + }).Build(t, nil, "") + + processor.PathProcMessageCollector = make(chan *processor.PathProcessorMessageResp, 10000) + + // Prep Interchain + const ibcPath = "gaia-osmosis" + ic := interchaintest.NewInterchain(). + AddChain(gaia). + AddChain(osmosis). + AddRelayer(r, "relayer"). + AddLink(interchaintest.InterchainLink{ + Chain1: gaia, + Chain2: osmosis, + Relayer: r, + Path: ibcPath, + }) + + // Reporter/logs + rep := testreporter.NewNopReporter() + eRep := rep.RelayerExecReporter(t) + + client, network := interchaintest.DockerSetup(t) + + // Build interchain + require.NoError(t, ic.Build(ctx, eRep, interchaintest.InterchainBuildOptions{ + TestName: t.Name(), + Client: client, + NetworkID: network, + + SkipPathCreation: false, + })) + + t.Parallel() + + // Make sure feegrant codec is registered, since it is not by default + feegrant.RegisterInterfaces(gaia.Config().EncodingConfig.InterfaceRegistry) + + // Get Channel ID + gaiaChans, err := r.GetChannels(ctx, eRep, gaia.Config().ChainID) + require.NoError(t, err) + gaiaChannel := gaiaChans[0] + osmosisChannel := gaiaChans[0].Counterparty + + // Create and Fund User Wallets + fundAmount := sdkmath.NewInt(10_000_000) + + // Tiny amount of funding, not enough to pay for a single TX fee (the GRANTER should be paying the fee) + granteeKeyPrefix := "grantee1" + grantee2KeyPrefix := "grantee2" + grantee3KeyPrefix := "grantee3" + granterKeyPrefix := "default" + + mnemonicAny := genMnemonic(t) + + gaiaGranteeWallet, err := buildUserUnfunded(ctx, granteeKeyPrefix, mnemonicAny, gaia) + require.NoError(t, err) + + mnemonicAny = genMnemonic(t) + gaiaGrantee2Wallet, err := buildUserUnfunded(ctx, grantee2KeyPrefix, mnemonicAny, gaia) + require.NoError(t, err) + + mnemonicAny = genMnemonic(t) + gaiaGrantee3Wallet, err := buildUserUnfunded(ctx, grantee3KeyPrefix, mnemonicAny, gaia) + require.NoError(t, err) + + mnemonicAny = genMnemonic(t) + osmosisUser, err := interchaintest.GetAndFundTestUserWithMnemonic(ctx, "recipient", mnemonicAny, fundAmount, osmosis) + require.NoError(t, err) + + mnemonicAny = genMnemonic(t) + gaiaUser, err := interchaintest.GetAndFundTestUserWithMnemonic(ctx, "recipient", mnemonicAny, fundAmount, gaia) + require.NoError(t, err) + + // Fund the granter wallet on chain + mnemonicAny = genMnemonic(t) + gaiaGranterWallet, err := interchaintest.GetAndFundTestUserWithMnemonic(ctx, granterKeyPrefix, mnemonicAny, fundAmount, gaia) + require.NoError(t, err) + + // Set SDK context to the right bech32 prefix + prefix := gaia.Config().Bech32Prefix + done := cosmos.SetSDKConfigContext(prefix) + + // Feegrant each of the grantees + err = Feegrant(t, gaia.(*cosmosv8.CosmosChain), gaiaGranterWallet, gaiaGranterWallet.Address(), gaiaGranteeWallet.Address(), gaiaGranterWallet.FormattedAddress(), gaiaGranteeWallet.FormattedAddress()) + require.NoError(t, err) + err = Feegrant(t, gaia.(*cosmosv8.CosmosChain), gaiaGranterWallet, gaiaGranterWallet.Address(), gaiaGrantee2Wallet.Address(), gaiaGranterWallet.FormattedAddress(), gaiaGrantee2Wallet.FormattedAddress()) + require.NoError(t, err) + err = Feegrant(t, gaia.(*cosmosv8.CosmosChain), gaiaGranterWallet, gaiaGranterWallet.Address(), gaiaGrantee3Wallet.Address(), gaiaGranterWallet.FormattedAddress(), gaiaGrantee3Wallet.FormattedAddress()) + require.NoError(t, err) + done() + + mnemonic := gaiaGranterWallet.Mnemonic() + fmt.Printf("Wallet mnemonic: %s\n", mnemonic) + + rand.Seed(time.Now().UnixNano()) + + // Notably, we do not restore the key for 'gaiaGranterWallet' to the relayer config. + // The relayer does not need the granter private key since it is owned externally. + // Below, the relayer restores the keys for each of the grantee wallets. It signs TXs with these keys. + // IBC chain config (above) is unrelated to RELAYER config so this step is necessary. + if err := r.RestoreKey(ctx, + eRep, + gaia.Config(), + gaiaGranteeWallet.KeyName(), + gaiaGranteeWallet.Mnemonic(), + ); err != nil { + t.Fatalf("failed to restore granter key to relayer for chain %s: %s", gaia.Config().ChainID, err.Error()) + } + + //IBC chain config is unrelated to RELAYER config so this step is necessary + if err := r.RestoreKey(ctx, + eRep, + gaia.Config(), + gaiaGrantee2Wallet.KeyName(), + gaiaGrantee2Wallet.Mnemonic(), + ); err != nil { + t.Fatalf("failed to restore granter key to relayer for chain %s: %s", gaia.Config().ChainID, err.Error()) + } + + //IBC chain config is unrelated to RELAYER config so this step is necessary + if err := r.RestoreKey(ctx, + eRep, + gaia.Config(), + gaiaGrantee3Wallet.KeyName(), + gaiaGrantee3Wallet.Mnemonic(), + ); err != nil { + t.Fatalf("failed to restore granter key to relayer for chain %s: %s", gaia.Config().ChainID, err.Error()) + } + + //IBC chain config is unrelated to RELAYER config so this step is necessary + if err := r.RestoreKey(ctx, + eRep, + osmosis.Config(), + osmosisUser.KeyName(), + osmosisUser.Mnemonic(), + ); err != nil { + t.Fatalf("failed to restore granter key to relayer for chain %s: %s", osmosis.Config().ChainID, err.Error()) + } + + //IBC chain config is unrelated to RELAYER config so this step is necessary + if err := r.RestoreKey(ctx, + eRep, + osmosis.Config(), + gaiaUser.KeyName(), + gaiaUser.Mnemonic(), + ); err != nil { + t.Fatalf("failed to restore granter key to relayer for chain %s: %s", gaia.Config().ChainID, err.Error()) + } + + gaiaGranteeAddr := gaiaGranteeWallet.FormattedAddress() + gaiaGrantee2Addr := gaiaGrantee2Wallet.FormattedAddress() + gaiaGrantee3Addr := gaiaGrantee3Wallet.FormattedAddress() + gaiaGranterAddr := gaiaGranterWallet.FormattedAddress() + + granteeCsv := gaiaGranteeWallet.KeyName() + "," + gaiaGrantee2Wallet.KeyName() + "," + gaiaGrantee3Wallet.KeyName() + + //You MUST run the configure feegrant command prior to starting the relayer, otherwise it'd be like you never set it up at all (within this test) + //Note that Gaia supports feegrants, but Osmosis does not (x/feegrant module, or any compatible module, is not included in Osmosis SDK app modules) + localRelayer := r.(*Relayer) + res := localRelayer.Sys().Run(logger, "chains", "configure", "feegrant", "basicallowance", gaia.Config().ChainID, gaiaGranterWallet.FormattedAddress(), "--grantees", granteeCsv, "--overwrite-granter") + if res.Err != nil { + fmt.Printf("configure feegrant results: %s\n", res.Stdout.String()) + t.Fatalf("failed to rly config feegrants: %v", res.Err) + } + + //Map of feegranted chains and the feegrant info for the chain + feegrantedChains := map[string]*chainFeegrantInfo{} + feegrantedChains[gaia.Config().ChainID] = &chainFeegrantInfo{granter: gaiaGranterAddr, grantees: []string{gaiaGranteeAddr, gaiaGrantee2Addr, gaiaGrantee3Addr}} + + time.Sleep(14 * time.Second) //commit a couple blocks + r.StartRelayer(ctx, eRep, ibcPath) + + // Send Transaction + amountToSend := sdkmath.NewInt(1_000) + + gaiaDstAddress := types.MustBech32ifyAddressBytes(osmosis.Config().Bech32Prefix, gaiaUser.Address()) + osmosisDstAddress := types.MustBech32ifyAddressBytes(gaia.Config().Bech32Prefix, osmosisUser.Address()) + + gaiaHeight, err := gaia.Height(ctx) + require.NoError(t, err) + + osmosisHeight, err := osmosis.Height(ctx) + require.NoError(t, err) + + var eg errgroup.Group + var gaiaTx ibc.Tx + + eg.Go(func() error { + gaiaTx, err = gaia.SendIBCTransfer(ctx, gaiaChannel.ChannelID, gaiaUser.KeyName(), ibc.WalletAmount{ + Address: gaiaDstAddress, + Denom: gaia.Config().Denom, + Amount: amountToSend, + }, + ibc.TransferOptions{}, + ) + if err != nil { + return err + } + if err := gaiaTx.Validate(); err != nil { + return err + } + + _, err = testutil.PollForAck(ctx, gaia, gaiaHeight, gaiaHeight+20, gaiaTx.Packet) + return err + }) + + eg.Go(func() error { + tx, err := osmosis.SendIBCTransfer(ctx, osmosisChannel.ChannelID, osmosisUser.KeyName(), ibc.WalletAmount{ + Address: osmosisDstAddress, + Denom: osmosis.Config().Denom, + Amount: amountToSend, + }, + ibc.TransferOptions{}, + ) + if err != nil { + return err + } + if err := tx.Validate(); err != nil { + return err + } + _, err = testutil.PollForAck(ctx, osmosis, osmosisHeight, osmosisHeight+20, tx.Packet) + return err + }) + + eg.Go(func() error { + tx, err := osmosis.SendIBCTransfer(ctx, osmosisChannel.ChannelID, osmosisUser.KeyName(), ibc.WalletAmount{ + Address: osmosisDstAddress, + Denom: osmosis.Config().Denom, + Amount: amountToSend, + }, + ibc.TransferOptions{}, + ) + if err != nil { + return err + } + if err := tx.Validate(); err != nil { + return err + } + _, err = testutil.PollForAck(ctx, osmosis, osmosisHeight, osmosisHeight+20, tx.Packet) + return err + }) + + eg.Go(func() error { + tx, err := osmosis.SendIBCTransfer(ctx, osmosisChannel.ChannelID, osmosisUser.KeyName(), ibc.WalletAmount{ + Address: osmosisDstAddress, + Denom: osmosis.Config().Denom, + Amount: amountToSend, + }, + ibc.TransferOptions{}, + ) + if err != nil { + return err + } + if err := tx.Validate(); err != nil { + return err + } + _, err = testutil.PollForAck(ctx, osmosis, osmosisHeight, osmosisHeight+20, tx.Packet) + return err + }) + + require.NoError(t, err) + require.NoError(t, eg.Wait()) + + feegrantMsgSigners := map[string][]string{} //chain to list of signers + + for len(processor.PathProcMessageCollector) > 0 { + select { + case curr, ok := <-processor.PathProcMessageCollector: + if ok && curr.Error == nil && curr.SuccessfulTx { + cProv, cosmProv := curr.DestinationChain.(*cosmos.CosmosProvider) + if cosmProv { + chain := cProv.PCfg.ChainID + feegrantInfo, isFeegrantedChain := feegrantedChains[chain] + if isFeegrantedChain && !strings.Contains(cProv.PCfg.KeyDirectory, t.Name()) { + //This would indicate that a parallel test is inserting msgs into the queue. + //We can safely skip over any messages inserted by other test cases. + fmt.Println("Skipping PathProcessorMessageResp from unrelated Parallel test case") + continue + } + + done := cProv.SetSDKContext() + + hash, err := hex.DecodeString(curr.Response.TxHash) + require.Nil(t, err) + txResp, err := TxWithRetry(ctx, cProv.RPCClient.Client, hash) + require.Nil(t, err) + + require.Nil(t, err) + dc := cProv.Cdc.TxConfig.TxDecoder() + tx, err := dc(txResp.Tx) + require.Nil(t, err) + builder, err := cProv.Cdc.TxConfig.WrapTxBuilder(tx) + require.Nil(t, err) + txFinder := builder.(protoTxProvider) + fullTx := txFinder.GetProtoTx() + isFeegrantedMsg := false + + msgs := "" + msgType := "" + for _, m := range fullTx.GetMsgs() { + msgType = types.MsgTypeURL(m) + //We want all IBC transfers (on an open channel/connection) to be feegranted in round robin fashion + if msgType == "/ibc.core.channel.v1.MsgRecvPacket" || msgType == "/ibc.core.channel.v1.MsgAcknowledgement" { + isFeegrantedMsg = true + msgs += msgType + ", " + } else { + msgs += msgType + ", " + } + } + + //It's required that TXs be feegranted in a round robin fashion for this chain and message type + if isFeegrantedChain && isFeegrantedMsg { + fmt.Printf("Msg types: %+v\n", msgs) + + signers, _, err := cProv.Cdc.Marshaler.GetMsgV1Signers(fullTx) + require.NoError(t, err) + + require.Equal(t, len(signers), 1) + granter := fullTx.FeeGranter(cProv.Cdc.Marshaler) + + //Feegranter for the TX that was signed on chain must be the relayer chain's configured feegranter + require.Equal(t, feegrantInfo.granter, string(granter)) + require.NotEmpty(t, granter) + + for _, msg := range fullTx.GetMsgs() { + msgType = types.MsgTypeURL(msg) + //We want all IBC transfers (on an open channel/connection) to be feegranted in round robin fashion + if msgType == "/ibc.core.channel.v1.MsgRecvPacket" { + c := msg.(*chantypes.MsgRecvPacket) + appData := c.Packet.GetData() + tokenTransfer := &transfertypes.FungibleTokenPacketData{} + err := tokenTransfer.Unmarshal(appData) + if err == nil { + fmt.Printf("%+v\n", tokenTransfer) + } else { + fmt.Println(string(appData)) + } + } + } + + //Grantee for the TX that was signed on chain must be a configured grantee in the relayer's chain feegrants. + //In addition, the grantee must be used in round robin fashion + //expectedGrantee := nextGrantee(feegrantInfo) + actualGrantee := string(signers[0]) + signerList, ok := feegrantMsgSigners[chain] + if ok { + signerList = append(signerList, actualGrantee) + feegrantMsgSigners[chain] = signerList + } else { + feegrantMsgSigners[chain] = []string{actualGrantee} + } + fmt.Printf("Chain: %s, msg type: %s, height: %d, signer: %s, granter: %s\n", chain, msgType, curr.Response.Height, actualGrantee, string(granter)) + } + done() + } + } + default: + fmt.Println("Unknown channel message") + } + } + + for chain, signers := range feegrantMsgSigners { + require.Equal(t, chain, gaia.Config().ChainID) + signerCountMap := map[string]int{} + + for _, signer := range signers { + count, ok := signerCountMap[signer] + if ok { + signerCountMap[signer] = count + 1 + } else { + signerCountMap[signer] = 1 + } + } + + highestCount := 0 + for _, count := range signerCountMap { + if count > highestCount { + highestCount = count + } + } + + //At least one feegranter must have signed a TX + require.GreaterOrEqual(t, highestCount, 1) + + //All of the feegrantees must have signed at least one TX + expectedFeegrantInfo := feegrantedChains[chain] + require.Equal(t, len(signerCountMap), len(expectedFeegrantInfo.grantees)) + + // verify that TXs were signed in a round robin fashion. + // no grantee should have signed more TXs than any other grantee (off by one is allowed). + for signer, count := range signerCountMap { + fmt.Printf("signer %s signed %d feegranted TXs \n", signer, count) + require.LessOrEqual(t, highestCount-count, 1) + } + } + + // Trace IBC Denom + gaiaDenomTrace := transfertypes.ParseDenomTrace(transfertypes.GetPrefixedDenom(osmosisChannel.PortID, osmosisChannel.ChannelID, gaia.Config().Denom)) + gaiaIbcDenom := gaiaDenomTrace.IBCDenom() + + osmosisDenomTrace := transfertypes.ParseDenomTrace(transfertypes.GetPrefixedDenom(gaiaChannel.PortID, gaiaChannel.ChannelID, osmosis.Config().Denom)) + osmosisIbcDenom := osmosisDenomTrace.IBCDenom() + + // Test destination wallets have increased funds + gaiaIBCBalance, err := osmosis.GetBalance(ctx, gaiaDstAddress, gaiaIbcDenom) + require.NoError(t, err) + require.True(t, amountToSend.Equal(gaiaIBCBalance)) + + osmosisIBCBalance, err := gaia.GetBalance(ctx, osmosisDstAddress, osmosisIbcDenom) + require.NoError(t, err) + require.True(t, amountToSend.MulRaw(3).Equal(osmosisIBCBalance)) + + // Test grantee still has exact amount expected + gaiaGranteeIBCBalance, err := gaia.GetBalance(ctx, gaiaGranteeAddr, gaia.Config().Denom) + require.NoError(t, err) + require.True(t, gaiaGranteeIBCBalance.Equal(sdkmath.ZeroInt())) + + // Test granter has less than they started with, meaning fees came from their account + gaiaGranterIBCBalance, err := gaia.GetBalance(ctx, gaiaGranterAddr, gaia.Config().Denom) + require.NoError(t, err) + require.True(t, gaiaGranterIBCBalance.LT(fundAmount)) + r.StopRelayer(ctx, eRep) + }) + } +} + +func buildUserUnfunded( + ctx context.Context, + keyNamePrefix, mnemonic string, + chain ibc.Chain, +) (ibc.Wallet, error) { + chainCfg := chain.Config() + keyName := fmt.Sprintf("%s-%s-%s", keyNamePrefix, chainCfg.ChainID, randLowerCaseLetterString(3)) + user, err := chain.BuildWallet(ctx, keyName, mnemonic) + if err != nil { + return nil, fmt.Errorf("failed to get source user wallet: %w", err) + } + + return user, nil +} + +var chars = []byte("abcdefghijklmnopqrstuvwxyz") + +// RandLowerCaseLetterString returns a lowercase letter string of given length +func randLowerCaseLetterString(length int) string { + b := make([]byte, length) + for i := range b { + b[i] = chars[rand.Intn(len(chars))] + } + return string(b) +} + +func Feegrant( + t *testing.T, + chain *cosmosv8.CosmosChain, + granterWallet ibc.Wallet, + granter types.AccAddress, + grantee types.AccAddress, + granterAddr string, + granteeAddr string, +) error { + // attempt to update client with duplicate header + b := cosmosv8.NewBroadcaster(t, chain) + + thirtyMin := time.Now().Add(30 * time.Minute) + feeGrantBasic := &feegrant.BasicAllowance{ + Expiration: &thirtyMin, + } + msgGrantAllowance, err := feegrant.NewMsgGrantAllowance(feeGrantBasic, granter, grantee) + if err != nil { + fmt.Printf("Error: feegrant.NewMsgGrantAllowance: %s", err.Error()) + return err + } + + // ensure correct bech32 prefix + msgGrantAllowance.Grantee = granteeAddr + msgGrantAllowance.Granter = granterAddr + + resp, err := cosmosv8.BroadcastTx(context.Background(), b, granterWallet, msgGrantAllowance) + require.NoError(t, err) + assertTransactionIsValid(t, resp) + return nil +} + +func assertTransactionIsValid(t *testing.T, resp types.TxResponse) { + t.Helper() + require.NotNil(t, resp) + require.NotEqual(t, 0, resp.GasUsed) + require.NotEqual(t, 0, resp.GasWanted) + require.Equal(t, uint32(0), resp.Code) + require.NotEmpty(t, resp.Data) + require.NotEmpty(t, resp.TxHash) + require.NotEmpty(t, resp.Events) +} diff --git a/interchaintest/go.mod b/interchaintest/go.mod index cefa3ab71..9f21d0447 100644 --- a/interchaintest/go.mod +++ b/interchaintest/go.mod @@ -46,6 +46,7 @@ require ( filippo.io/edwards25519 v1.0.0 // indirect github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 // indirect github.com/99designs/keyring v1.2.2 // indirect + github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 // indirect github.com/BurntSushi/toml v1.3.2 // indirect github.com/ChainSafe/go-schnorrkel v1.0.0 // indirect github.com/ChainSafe/go-schnorrkel/1 v0.0.0-00010101000000-000000000000 // indirect @@ -101,6 +102,7 @@ require ( github.com/dgryski/go-farm v0.0.0-20200201041132-a6ae2369ad13 // indirect github.com/docker/distribution v2.8.2+incompatible // indirect github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-metrics v0.0.1 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/dvsekhvalnov/jose2go v1.6.0 // indirect @@ -185,6 +187,8 @@ require ( github.com/mmcloughlin/addchain v0.4.0 // indirect github.com/moby/patternmatcher v0.5.0 // indirect github.com/moby/sys/sequential v0.5.0 // indirect + github.com/moby/term v0.0.0-20221205130635-1aeaba878587 // indirect + github.com/morikuni/aec v1.0.0 // indirect github.com/mr-tron/base58 v1.2.0 // indirect github.com/mtibben/percent v0.2.1 // indirect github.com/multiformats/go-base32 v0.1.0 // indirect @@ -212,6 +216,7 @@ require ( github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect + github.com/rootless-containers/rootlesskit v1.1.1 // indirect github.com/rs/cors v1.8.3 // indirect github.com/rs/zerolog v1.31.0 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect diff --git a/interchaintest/go.sum b/interchaintest/go.sum index 54ea4b568..011bdafae 100644 --- a/interchaintest/go.sum +++ b/interchaintest/go.sum @@ -397,6 +397,8 @@ github.com/containerd/containerd v1.7.11 h1:lfGKw3eU35sjV0aG2eYZTiwFEY1pCzxdzicH github.com/containerd/containerd v1.7.11/go.mod h1:5UluHxHTX2rdvYuZ5OJTC5m/KJNs0Zs9wVoJm9zf5ZE= github.com/containerd/continuity v0.4.2 h1:v3y/4Yz5jwnvqPKJJ+7Wf93fyWoCB3F5EclWG023MDM= github.com/containerd/continuity v0.4.2/go.mod h1:F6PTNCKepoxEaXLQp3wDAjygEnImnZ/7o4JzpodfroQ= +github.com/containerd/fifo v1.1.0 h1:4I2mbh5stb1u6ycIABlBw9zgtlK8viPI9QkQNRQEEmY= +github.com/containerd/fifo v1.1.0/go.mod h1:bmC4NWMbXlt2EZ0Hc7Fx7QzTFxgPID13eH0Qu+MAb2o= github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= @@ -437,6 +439,8 @@ github.com/crate-crypto/go-kzg-4844 v0.7.0 h1:C0vgZRk4q4EZ/JgPfzuSoxdCq3C3mOZMBS github.com/crate-crypto/go-kzg-4844 v0.7.0/go.mod h1:1kMhvPgI0Ky3yIa+9lFySEBUBXkYxeOi8ZF1sYioxhc= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/creack/pty v1.1.18 h1:n56/Zwd5o6whRC5PMGretI4IdRLlmBXYNjScPaBgsbY= +github.com/creack/pty v1.1.18/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= github.com/danieljoos/wincred v1.1.2 h1:QLdCxFs1/Yl4zduvBdcHB8goaYk9RARS2SgLLRuAyr0= github.com/danieljoos/wincred v1.1.2/go.mod h1:GijpziifJoIBfYh+S7BbkdUTU4LfM+QnGqR5Vl2tAx0= @@ -479,6 +483,8 @@ github.com/docker/docker v24.0.7+incompatible h1:Wo6l37AuwP3JaMnZa226lzVXGA3F9Ig github.com/docker/docker v24.0.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-metrics v0.0.1 h1:AgB/0SvBxihN0X8OR4SjsblXkbMvalQ8cjmtKQ2rQV8= +github.com/docker/go-metrics v0.0.1/go.mod h1:cG1hvH2utMXtqgqqYE9plW6lDxS3/5ayHzueweSI3Vw= github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= @@ -1066,6 +1072,7 @@ github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndr github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_golang v1.1.0/go.mod h1:I1FGZT9+L76gKKOs5djB6ezCbFQP1xR9D75/vuwEF3g= github.com/prometheus/client_golang v1.3.0/go.mod h1:hJaj2vgQTGQmVCsAACORcieXFeDPbaTKGT+JTgUa3og= github.com/prometheus/client_golang v1.4.0/go.mod h1:e9GMxYsXl05ICDXkRhurwBS4Q3OK1iX/F2sw+iXX5zU= github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= @@ -1081,6 +1088,7 @@ github.com/prometheus/client_model v0.5.0 h1:VQw1hfvPvk3Uv6Qf29VrPF32JB6rtbgI6cY github.com/prometheus/client_model v0.5.0/go.mod h1:dTiFglRmd66nLR9Pv9f0mZi7B7fk5Pm3gvsjB5tr+kI= github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= github.com/prometheus/common v0.7.0/go.mod h1:DjGbpBbp5NYNiECxcL/VnbXCCaQpKd3tt26CguLLsqA= github.com/prometheus/common v0.9.1/go.mod h1:yhUN8i9wzaXS3w1O07YhxHEBxD+W35wd8bs7vj7HSQ4= github.com/prometheus/common v0.10.0/go.mod h1:Tlit/dnDKsSWFlCLTWaA1cyBgKHSMdTB80sz/V91rCo= @@ -1090,6 +1098,7 @@ github.com/prometheus/common v0.45.0/go.mod h1:YJmSTw9BoKxJplESWWxlbyttQR4uaEcGy github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.3.0/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= @@ -1110,6 +1119,8 @@ github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFR github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= +github.com/rootless-containers/rootlesskit v1.1.1 h1:F5psKWoWY9/VjZ3ifVcaosjvFZJOagX85U22M0/EQZE= +github.com/rootless-containers/rootlesskit v1.1.1/go.mod h1:UD5GoA3dqKCJrnvnhVgQQnweMF2qZnf9KLw8EewcMZI= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/cors v1.8.3 h1:O+qNyWn7Z+F9M0ILBHgMVPuB1xTOucVd5gtaYyXBpRo= github.com/rs/cors v1.8.3/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= @@ -1457,6 +1468,7 @@ golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190801041406-cbf593c0f2f3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190826190057-c7b8b68b1456/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/relayer/chains/cosmos/bech32_hack.go b/relayer/chains/cosmos/bech32_hack.go index 96bb81c9a..6bbfde67a 100644 --- a/relayer/chains/cosmos/bech32_hack.go +++ b/relayer/chains/cosmos/bech32_hack.go @@ -14,10 +14,15 @@ var sdkConfigMutex sync.Mutex // Don't use this unless you know what you're doing. // TODO: :dagger: :knife: :chainsaw: remove this function func (cc *CosmosProvider) SetSDKContext() func() { + return SetSDKConfigContext(cc.PCfg.AccountPrefix) +} + +// SetSDKContext sets the SDK config to the given bech32 prefixes +func SetSDKConfigContext(prefix string) func() { sdkConfigMutex.Lock() sdkConf := sdk.GetConfig() - sdkConf.SetBech32PrefixForAccount(cc.PCfg.AccountPrefix, cc.PCfg.AccountPrefix+"pub") - sdkConf.SetBech32PrefixForValidator(cc.PCfg.AccountPrefix+"valoper", cc.PCfg.AccountPrefix+"valoperpub") - sdkConf.SetBech32PrefixForConsensusNode(cc.PCfg.AccountPrefix+"valcons", cc.PCfg.AccountPrefix+"valconspub") + sdkConf.SetBech32PrefixForAccount(prefix, prefix+"pub") + sdkConf.SetBech32PrefixForValidator(prefix+"valoper", prefix+"valoperpub") + sdkConf.SetBech32PrefixForConsensusNode(prefix+"valcons", prefix+"valconspub") return sdkConfigMutex.Unlock } diff --git a/relayer/chains/cosmos/codec.go b/relayer/chains/cosmos/codec.go index b3ec9ffbc..180c26750 100644 --- a/relayer/chains/cosmos/codec.go +++ b/relayer/chains/cosmos/codec.go @@ -2,9 +2,11 @@ package cosmos import ( feegrant "cosmossdk.io/x/feegrant/module" + "cosmossdk.io/x/tx/signing" "cosmossdk.io/x/upgrade" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/codec" + "github.com/cosmos/cosmos-sdk/codec/address" "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/std" "github.com/cosmos/cosmos-sdk/types/module" @@ -21,6 +23,7 @@ import ( paramsclient "github.com/cosmos/cosmos-sdk/x/params/client" "github.com/cosmos/cosmos-sdk/x/slashing" "github.com/cosmos/cosmos-sdk/x/staking" + "github.com/cosmos/gogoproto/proto" "github.com/cosmos/ibc-go/modules/capability" ibcfee "github.com/cosmos/ibc-go/v8/modules/apps/29-fee" "github.com/cosmos/ibc-go/v8/modules/apps/transfer" @@ -66,9 +69,9 @@ type Codec struct { Amino *codec.LegacyAmino } -func MakeCodec(moduleBasics []module.AppModuleBasic, extraCodecs []string) Codec { +func MakeCodec(moduleBasics []module.AppModuleBasic, extraCodecs []string, accBech32Prefix, valBech32Prefix string) Codec { modBasic := module.NewBasicManager(moduleBasics...) - encodingConfig := MakeCodecConfig() + encodingConfig := MakeCodecConfig(accBech32Prefix, valBech32Prefix) std.RegisterLegacyAminoCodec(encodingConfig.Amino) std.RegisterInterfaces(encodingConfig.InterfaceRegistry) modBasic.RegisterLegacyAminoCodec(encodingConfig.Amino) @@ -89,9 +92,22 @@ func MakeCodec(moduleBasics []module.AppModuleBasic, extraCodecs []string) Codec return encodingConfig } -func MakeCodecConfig() Codec { - interfaceRegistry := types.NewInterfaceRegistry() +func MakeCodecConfig(accBech32Prefix, valBech32Prefix string) Codec { + interfaceRegistry, err := types.NewInterfaceRegistryWithOptions(types.InterfaceRegistryOptions{ + ProtoFiles: proto.HybridResolver, + SigningOptions: signing.Options{ + AddressCodec: address.NewBech32Codec(accBech32Prefix), + ValidatorAddressCodec: address.NewBech32Codec(valBech32Prefix), + }, + }) + if err != nil { + panic(err) + } marshaler := codec.NewProtoCodec(interfaceRegistry) + + done := SetSDKConfigContext(accBech32Prefix) + defer done() + return Codec{ InterfaceRegistry: interfaceRegistry, Marshaler: marshaler, diff --git a/relayer/chains/cosmos/feegrant.go b/relayer/chains/cosmos/feegrant.go index 9d1b5840c..0d1ef1f4e 100644 --- a/relayer/chains/cosmos/feegrant.go +++ b/relayer/chains/cosmos/feegrant.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "regexp" "strconv" "time" @@ -12,8 +11,10 @@ import ( "cosmossdk.io/x/feegrant" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/crypto/hd" + "github.com/cosmos/cosmos-sdk/types" sdk "github.com/cosmos/cosmos-sdk/types" txtypes "github.com/cosmos/cosmos-sdk/types/tx" + "go.uber.org/zap" ) // Searches for valid, existing BasicAllowance grants for the ChainClient's configured Feegranter. @@ -25,7 +26,7 @@ func (cc *CosmosProvider) GetValidBasicGrants() ([]*feegrant.Grant, error) { return nil, errors.New("no feegrant configuration for chainclient") } - keyNameOrAddress := cc.PCfg.FeeGrants.GranterKey + keyNameOrAddress := cc.PCfg.FeeGrants.GranterKeyOrAddr address, err := cc.AccountFromKeyOrAddress(keyNameOrAddress) if err != nil { return nil, err @@ -40,18 +41,19 @@ func (cc *CosmosProvider) GetValidBasicGrants() ([]*feegrant.Grant, error) { for _, grant := range grants { switch grant.Allowance.TypeUrl { case "/cosmos.feegrant.v1beta1.BasicAllowance": - //var feegrantAllowance feegrant.BasicAllowance var feegrantAllowance feegrant.FeeAllowanceI e := cc.Cdc.InterfaceRegistry.UnpackAny(grant.Allowance, &feegrantAllowance) if e != nil { return nil, e } - //feegrantAllowance := grant.Allowance.GetCachedValue().(*feegrant.BasicAllowance) if isValidGrant(feegrantAllowance.(*feegrant.BasicAllowance)) { validGrants = append(validGrants, grant) } default: - fmt.Printf("Ignoring grant type %s for granter %s and grantee %s\n", grant.Allowance.TypeUrl, grant.Granter, grant.Grantee) + cc.log.Debug("Ignoring grant", + zap.String("type", grant.Allowance.TypeUrl), + zap.String("granter", grant.Granter), + zap.String("grantee", grant.Grantee)) } } @@ -67,7 +69,7 @@ func (cc *CosmosProvider) GetGranteeValidBasicGrants(granteeKey string) ([]*feeg return nil, errors.New("no feegrant configuration for chainclient") } - granterAddr, err := cc.AccountFromKeyOrAddress(cc.PCfg.FeeGrants.GranterKey) + granterAddr, err := cc.AccountFromKeyOrAddress(cc.PCfg.FeeGrants.GranterKeyOrAddr) if err != nil { return nil, err } @@ -97,7 +99,10 @@ func (cc *CosmosProvider) GetGranteeValidBasicGrants(granteeKey string) ([]*feeg validGrants = append(validGrants, grant) } default: - fmt.Printf("Ignoring grant type %s for granter %s and grantee %s\n", grant.Allowance.TypeUrl, grant.Granter, grant.Grantee) + cc.log.Debug("Ignoring grant", + zap.String("type", grant.Allowance.TypeUrl), + zap.String("granter", grant.Granter), + zap.String("grantee", grant.Grantee)) } } } @@ -130,9 +135,9 @@ func isValidGrant(a *feegrant.BasicAllowance) bool { func (cc *CosmosProvider) ConfigureFeegrants(numGrantees int, granterKey string) error { cc.PCfg.FeeGrants = &FeeGrantConfiguration{ - GranteesWanted: numGrantees, - GranterKey: granterKey, - ManagedGrantees: []string{}, + GranteesWanted: numGrantees, + GranterKeyOrAddr: granterKey, + ManagedGrantees: []string{}, } return cc.PCfg.FeeGrants.AddGranteeKeys(cc) @@ -144,14 +149,14 @@ func (cc *CosmosProvider) ConfigureWithGrantees(grantees []string, granterKey st } cc.PCfg.FeeGrants = &FeeGrantConfiguration{ - GranteesWanted: len(grantees), - GranterKey: granterKey, - ManagedGrantees: grantees, + GranteesWanted: len(grantees), + GranterKeyOrAddr: granterKey, + ManagedGrantees: grantees, } for _, newGrantee := range grantees { if !cc.KeyExists(newGrantee) { - //Add another key to the chain client for the grantee + // Add another key to the chain client for the grantee _, err := cc.AddKey(newGrantee, sdk.CoinType, string(hd.Secp256k1Type)) if err != nil { return err @@ -162,12 +167,36 @@ func (cc *CosmosProvider) ConfigureWithGrantees(grantees []string, granterKey st return nil } +func (cc *CosmosProvider) ConfigureWithExternalGranter(grantees []string, granterAddr string) error { + if len(grantees) == 0 { + return errors.New("list of grantee names cannot be empty") + } + + cc.PCfg.FeeGrants = &FeeGrantConfiguration{ + GranteesWanted: len(grantees), + GranterKeyOrAddr: granterAddr, + ManagedGrantees: grantees, + IsExternalGranter: true, + } + + for _, grantee := range grantees { + k, err := cc.KeyFromKeyOrAddress(grantee) + if k == "" { + return fmt.Errorf("invalid empty grantee name") + } else if err != nil { + return err + } + } + + return nil +} + func (fg *FeeGrantConfiguration) AddGranteeKeys(cc *CosmosProvider) error { for i := len(fg.ManagedGrantees); i < fg.GranteesWanted; i++ { newGranteeIdx := strconv.Itoa(len(fg.ManagedGrantees) + 1) newGrantee := "grantee" + newGranteeIdx - //Add another key to the chain client for the grantee + // Add another key to the chain client for the grantee _, err := cc.AddKey(newGrantee, sdk.CoinType, string(hd.Secp256k1Type)) if err != nil { return err @@ -181,34 +210,32 @@ func (fg *FeeGrantConfiguration) AddGranteeKeys(cc *CosmosProvider) error { // Get the feegrant params to use for the next TX. If feegrants are not configured for the chain client, the default key will be used for TX signing. // Otherwise, a configured feegrantee will be chosen for TX signing in round-robin fashion. -func (cc *CosmosProvider) GetTxFeeGrant() (txSignerKey string, feeGranterKey string) { - //By default, we should sign TXs with the ChainClient's default key +func (cc *CosmosProvider) GetTxFeeGrant() (txSignerKey string, feeGranterKeyOrAddr string) { + // By default, we should sign TXs with the ChainClient's default key txSignerKey = cc.PCfg.Key if cc.PCfg.FeeGrants == nil { - fmt.Printf("cc.Config.FeeGrants == nil\n") return } // Use the ChainClient's configured Feegranter key for the next TX. - feeGranterKey = cc.PCfg.FeeGrants.GranterKey + feeGranterKeyOrAddr = cc.PCfg.FeeGrants.GranterKeyOrAddr // The ChainClient Feegrant configuration has never been verified on chain. // Don't use Feegrants as it could cause the TX to fail on chain. - if feeGranterKey == "" || cc.PCfg.FeeGrants.BlockHeightVerified <= 0 { - fmt.Printf("cc.Config.FeeGrants.BlockHeightVerified <= 0\n") - feeGranterKey = "" + if feeGranterKeyOrAddr == "" || cc.PCfg.FeeGrants.BlockHeightVerified <= 0 { + feeGranterKeyOrAddr = "" return } - //Pick the next managed grantee in the list as the TX signer + // Pick the next managed grantee in the list as the TX signer lastGranteeIdx := cc.PCfg.FeeGrants.GranteeLastSignerIndex if lastGranteeIdx >= 0 && lastGranteeIdx <= len(cc.PCfg.FeeGrants.ManagedGrantees)-1 { txSignerKey = cc.PCfg.FeeGrants.ManagedGrantees[lastGranteeIdx] cc.PCfg.FeeGrants.GranteeLastSignerIndex = cc.PCfg.FeeGrants.GranteeLastSignerIndex + 1 - //Restart the round robin at 0 if we reached the end of the list of grantees + // Restart the round robin at 0 if we reached the end of the list of grantees if cc.PCfg.FeeGrants.GranteeLastSignerIndex == len(cc.PCfg.FeeGrants.ManagedGrantees) { cc.PCfg.FeeGrants.GranteeLastSignerIndex = 0 } @@ -219,27 +246,40 @@ func (cc *CosmosProvider) GetTxFeeGrant() (txSignerKey string, feeGranterKey str // Ensure all Basic Allowance grants are in place for the given ChainClient. // This will query (RPC) for existing grants and create new grants if they don't exist. -func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string) (*sdk.TxResponse, error) { +func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string, gas uint64) (*sdk.TxResponse, error) { if cc.PCfg.FeeGrants == nil { - return nil, errors.New("ChainClient must be a FeeGranter to establish grants") + return nil, errors.New("chain client must be a FeeGranter to establish grants") } else if len(cc.PCfg.FeeGrants.ManagedGrantees) == 0 { - return nil, errors.New("ChainClient is a FeeGranter, but is not managing any Grantees") + return nil, errors.New("chain client is a FeeGranter, but is not managing any Grantees") } - granterKey := cc.PCfg.FeeGrants.GranterKey + var granterAddr string + var granterAcc types.AccAddress + var err error + + granterKey := cc.PCfg.FeeGrants.GranterKeyOrAddr if granterKey == "" { granterKey = cc.PCfg.Key } - granterAcc, err := cc.GetKeyAddressForKey(granterKey) - if err != nil { - fmt.Printf("Retrieving key '%s': ChainClient FeeGranter misconfiguration: %s", granterKey, err.Error()) - return nil, err - } + if cc.PCfg.FeeGrants.IsExternalGranter { + _, err := cc.DecodeBech32AccAddr(granterKey) + if err != nil { + return nil, fmt.Errorf("an unknown granter was specified: '%s' is not a valid bech32 address", granterKey) + } - granterAddr, granterAddrErr := cc.EncodeBech32AccAddr(granterAcc) - if granterAddrErr != nil { - return nil, granterAddrErr + granterAddr = granterKey + } else { + granterAcc, err = cc.GetKeyAddressForKey(granterKey) + if err != nil { + cc.log.Error("Unknown key", zap.String("name", granterKey)) + return nil, err + } + + granterAddr, err = cc.EncodeBech32AccAddr(granterAcc) + if err != nil { + return nil, err + } } validGrants, err := cc.GetValidBasicGrants() @@ -250,9 +290,8 @@ func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string) (* grantsNeeded := 0 for _, grantee := range cc.PCfg.FeeGrants.ManagedGrantees { - - //Searching for all grants with the given granter failed, so we will search by the grantee. - //Reason this lookup sometimes fails is because the 'Search by granter' request is in SDK v0.46+ + // Searching for all grants with the given granter failed, so we will search by the grantee. + // Reason this lookup sometimes fails is because the 'Search by granter' request is in SDK v0.46+ if failedLookupGrantsByGranter { validGrants, err = cc.GetGranteeValidBasicGrants(grantee) if err != nil { @@ -262,7 +301,7 @@ func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string) (* granteeAcc, err := cc.GetKeyAddressForKey(grantee) if err != nil { - fmt.Printf("Misconfiguration for grantee key %s. Error: %s\n", grantee, err.Error()) + cc.log.Error("Unknown grantee", zap.String("key_name", grantee)) return nil, err } @@ -274,19 +313,21 @@ func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string) (* hasGrant := false for _, basicGrant := range validGrants { if basicGrant.Grantee == granteeAddr { - fmt.Printf("Valid grant found for granter %s, grantee %s\n", basicGrant.Granter, basicGrant.Grantee) hasGrant = true } } - if !hasGrant { - grantsNeeded += 1 - fmt.Printf("Grant will be created on chain for granter %s and grantee %s\n", granterAddr, granteeAddr) + if !hasGrant && !cc.PCfg.FeeGrants.IsExternalGranter { + grantsNeeded++ + cc.log.Info("Creating feegrant", zap.String("granter", granterAddr), zap.String("grantee", granteeAddr)) + grantMsg, err := cc.getMsgGrantBasicAllowance(granterAcc, granteeAcc) if err != nil { return nil, err } msgs = append(msgs, grantMsg) + } else if !hasGrant { + cc.log.Warn("Missing feegrant", zap.String("external_granter", granterAddr), zap.String("grantee", granteeAddr)) } } @@ -299,37 +340,24 @@ func (cc *CosmosProvider) EnsureBasicGrants(ctx context.Context, memo string) (* granterExists := cc.EnsureExists(cliCtx, granterAcc) == nil - //Feegranter exists on chain + // Feegranter exists on chain if granterExists { - txResp, err := cc.SubmitTxAwaitResponse(ctx, msgs, memo, 0, granterKey) + txResp, err := cc.SubmitTxAwaitResponse(ctx, msgs, memo, gas, granterKey) if err != nil { - fmt.Printf("Error: SubmitTxAwaitResponse: %s", err.Error()) return nil, err } else if txResp != nil && txResp.TxResponse != nil && txResp.TxResponse.Code != 0 { - fmt.Printf("Submitting grants for granter %s failed. Code: %d, TX hash: %s\n", granterKey, txResp.TxResponse.Code, txResp.TxResponse.TxHash) + cc.log.Warn("Feegrant TX failed", zap.String("tx_hash", txResp.TxResponse.TxHash), zap.Uint32("code", txResp.TxResponse.Code)) return nil, fmt.Errorf("could not configure feegrant for granter %s", granterKey) } - fmt.Printf("TX succeeded, %d new grants configured, %d grants already in place. TX hash: %s\n", grantsNeeded, numGrantees-grantsNeeded, txResp.TxResponse.TxHash) + cc.log.Info("Feegrant succeeded", zap.Int("new_grants", grantsNeeded), zap.Int("existing_grants", numGrantees-grantsNeeded), zap.String("tx_hash", txResp.TxResponse.TxHash)) return txResp.TxResponse, err - } else { - return nil, fmt.Errorf("granter %s does not exist on chain", granterKey) } - } else { - fmt.Printf("All grantees (%d total) already had valid feegrants. Feegrant configuration verified.\n", numGrantees) - } - return nil, nil -} - -func getGasTokenDenom(gasPrices string) (string, error) { - r := regexp.MustCompile(`(?P[0-9.]*)(?P.*)`) - submatches := r.FindStringSubmatch(gasPrices) - if len(submatches) != 3 { - return "", errors.New("could not find fee denom") + return nil, fmt.Errorf("granter %s does not exist on chain", granterKey) } - return submatches[2], nil + return nil, nil } // GrantBasicAllowance Send a feegrant with the basic allowance type. @@ -337,18 +365,18 @@ func getGasTokenDenom(gasPrices string) (string, error) { // TODO: check for existing authorizations prior to attempting new one. func (cc *CosmosProvider) GrantAllGranteesBasicAllowance(ctx context.Context, gas uint64) error { if cc.PCfg.FeeGrants == nil { - return errors.New("ChainClient must be a FeeGranter to establish grants") + return errors.New("chain client must be a FeeGranter to establish grants") } else if len(cc.PCfg.FeeGrants.ManagedGrantees) == 0 { - return errors.New("ChainClient is a FeeGranter, but is not managing any Grantees") + return errors.New("chain client is a FeeGranter, but is not managing any Grantees") } - granterKey := cc.PCfg.FeeGrants.GranterKey + granterKey := cc.PCfg.FeeGrants.GranterKeyOrAddr if granterKey == "" { granterKey = cc.PCfg.Key } granterAddr, err := cc.GetKeyAddressForKey(granterKey) if err != nil { - fmt.Printf("ChainClient FeeGranter misconfiguration: %s", err.Error()) + cc.log.Error("Unknown granter", zap.String("key_name", granterKey)) return err } @@ -356,7 +384,7 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowance(ctx context.Context, ga granteeAddr, err := cc.GetKeyAddressForKey(grantee) if err != nil { - fmt.Printf("Misconfiguration for grantee %s. Error: %s\n", grantee, err.Error()) + cc.log.Error("Unknown grantee", zap.String("key_name", grantee)) return err } @@ -364,7 +392,6 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowance(ctx context.Context, ga if err != nil { return err } else if grantResp != nil && grantResp.TxResponse != nil && grantResp.TxResponse.Code != 0 { - fmt.Printf("grantee %s and granter %s. Code: %d\n", granterAddr.String(), granteeAddr.String(), grantResp.TxResponse.Code) return fmt.Errorf("could not configure feegrant for granter %s and grantee %s", granterAddr.String(), granteeAddr.String()) } } @@ -373,22 +400,21 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowance(ctx context.Context, ga // GrantBasicAllowance Send a feegrant with the basic allowance type. // This function does not check for existing feegrant authorizations. -// TODO: check for existing authorizations prior to attempting new one. func (cc *CosmosProvider) GrantAllGranteesBasicAllowanceWithExpiration(ctx context.Context, gas uint64, expiration time.Time) error { if cc.PCfg.FeeGrants == nil { - return errors.New("ChainClient must be a FeeGranter to establish grants") + return errors.New("chain client must be a FeeGranter to establish grants") } else if len(cc.PCfg.FeeGrants.ManagedGrantees) == 0 { - return errors.New("ChainClient is a FeeGranter, but is not managing any Grantees") + return errors.New("chain client is a FeeGranter, but is not managing any Grantees") } - granterKey := cc.PCfg.FeeGrants.GranterKey + granterKey := cc.PCfg.FeeGrants.GranterKeyOrAddr if granterKey == "" { granterKey = cc.PCfg.Key } granterAddr, err := cc.GetKeyAddressForKey(granterKey) if err != nil { - fmt.Printf("ChainClient FeeGranter misconfiguration: %s", err.Error()) + cc.log.Error("Unknown granter", zap.String("key_name", granterKey)) return err } @@ -396,7 +422,7 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowanceWithExpiration(ctx conte granteeAddr, err := cc.GetKeyAddressForKey(grantee) if err != nil { - fmt.Printf("Misconfiguration for grantee %s. Error: %s\n", grantee, err.Error()) + cc.log.Error("Unknown grantee", zap.String("key_name", grantee)) return err } @@ -404,7 +430,6 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowanceWithExpiration(ctx conte if err != nil { return err } else if grantResp != nil && grantResp.TxResponse != nil && grantResp.TxResponse.Code != 0 { - fmt.Printf("grantee %s and granter %s. Code: %d\n", granterAddr.String(), granteeAddr.String(), grantResp.TxResponse.Code) return fmt.Errorf("could not configure feegrant for granter %s and grantee %s", granterAddr.String(), granteeAddr.String()) } } @@ -412,35 +437,30 @@ func (cc *CosmosProvider) GrantAllGranteesBasicAllowanceWithExpiration(ctx conte } func (cc *CosmosProvider) getMsgGrantBasicAllowanceWithExpiration(granter sdk.AccAddress, grantee sdk.AccAddress, expiration time.Time) (sdk.Msg, error) { - //thirtyMin := time.Now().Add(30 * time.Minute) feeGrantBasic := &feegrant.BasicAllowance{ Expiration: &expiration, } msgGrantAllowance, err := feegrant.NewMsgGrantAllowance(feeGrantBasic, granter, grantee) if err != nil { - fmt.Printf("Error: GrantBasicAllowance.NewMsgGrantAllowance: %s", err.Error()) return nil, err } - //Due to the way Lens configures the SDK, addresses will have the 'cosmos' prefix which - //doesn't necessarily match the chain prefix of the ChainClient config. So calling the internal - //'NewMsgGrantAllowance' function will return the *incorrect* 'cosmos' prefixed bech32 address. - - //Update the Grant to ensure the correct chain-specific granter is set + // Update the Grant to ensure the correct chain-specific granter is set granterAddr, granterAddrErr := cc.EncodeBech32AccAddr(granter) if granterAddrErr != nil { - fmt.Printf("EncodeBech32AccAddr: %s", granterAddrErr.Error()) return nil, granterAddrErr } - //Update the Grant to ensure the correct chain-specific grantee is set + // Update the Grant to ensure the correct chain-specific grantee is set granteeAddr, granteeAddrErr := cc.EncodeBech32AccAddr(grantee) if granteeAddrErr != nil { - fmt.Printf("EncodeBech32AccAddr: %s", granteeAddrErr.Error()) return nil, granteeAddrErr } - //override the 'cosmos' prefixed bech32 addresses with the correct chain prefix + // Due to the way Lens configures the SDK, addresses will have the 'cosmos' prefix which + // doesn't necessarily match the chain prefix of the ChainClient config. So calling the internal + // 'NewMsgGrantAllowance' function will return the *incorrect* 'cosmos' prefixed bech32 address. + // override the 'cosmos' prefixed bech32 addresses with the correct chain prefix msgGrantAllowance.Grantee = granteeAddr msgGrantAllowance.Granter = granterAddr @@ -448,35 +468,28 @@ func (cc *CosmosProvider) getMsgGrantBasicAllowanceWithExpiration(granter sdk.Ac } func (cc *CosmosProvider) getMsgGrantBasicAllowance(granter sdk.AccAddress, grantee sdk.AccAddress) (sdk.Msg, error) { - //thirtyMin := time.Now().Add(30 * time.Minute) - feeGrantBasic := &feegrant.BasicAllowance{ - //Expiration: &thirtyMin, - } + feeGrantBasic := &feegrant.BasicAllowance{} msgGrantAllowance, err := feegrant.NewMsgGrantAllowance(feeGrantBasic, granter, grantee) if err != nil { - fmt.Printf("Error: GrantBasicAllowance.NewMsgGrantAllowance: %s", err.Error()) return nil, err } - //Due to the way Lens configures the SDK, addresses will have the 'cosmos' prefix which - //doesn't necessarily match the chain prefix of the ChainClient config. So calling the internal - //'NewMsgGrantAllowance' function will return the *incorrect* 'cosmos' prefixed bech32 address. - - //Update the Grant to ensure the correct chain-specific granter is set + // Update the Grant to ensure the correct chain-specific granter is set granterAddr, granterAddrErr := cc.EncodeBech32AccAddr(granter) if granterAddrErr != nil { - fmt.Printf("EncodeBech32AccAddr: %s", granterAddrErr.Error()) return nil, granterAddrErr } - //Update the Grant to ensure the correct chain-specific grantee is set + // Update the Grant to ensure the correct chain-specific grantee is set granteeAddr, granteeAddrErr := cc.EncodeBech32AccAddr(grantee) if granteeAddrErr != nil { - fmt.Printf("EncodeBech32AccAddr: %s", granteeAddrErr.Error()) return nil, granteeAddrErr } - //override the 'cosmos' prefixed bech32 addresses with the correct chain prefix + // Due to the way Lens configures the SDK, addresses will have the 'cosmos' prefix which + // doesn't necessarily match the chain prefix of the ChainClient config. So calling the internal + // 'NewMsgGrantAllowance' function will return the *incorrect* 'cosmos' prefixed bech32 address. + // override the 'cosmos' prefixed bech32 addresses with the correct chain prefix msgGrantAllowance.Grantee = granteeAddr msgGrantAllowance.Granter = granterAddr @@ -492,7 +505,6 @@ func (cc *CosmosProvider) GrantBasicAllowance(ctx context.Context, granter sdk.A msgs := []sdk.Msg{msgGrantAllowance} txResp, err := cc.SubmitTxAwaitResponse(ctx, msgs, "", gas, granterKeyName) if err != nil { - fmt.Printf("Error: GrantBasicAllowance.SubmitTxAwaitResponse: %s", err.Error()) return nil, err } @@ -508,7 +520,6 @@ func (cc *CosmosProvider) GrantBasicAllowanceWithExpiration(ctx context.Context, msgs := []sdk.Msg{msgGrantAllowance} txResp, err := cc.SubmitTxAwaitResponse(ctx, msgs, "", gas, granterKeyName) if err != nil { - fmt.Printf("Error: GrantBasicAllowance.SubmitTxAwaitResponse: %s", err.Error()) return nil, err } diff --git a/relayer/chains/cosmos/keys.go b/relayer/chains/cosmos/keys.go index ce6c2a2ef..ff4ecdb05 100644 --- a/relayer/chains/cosmos/keys.go +++ b/relayer/chains/cosmos/keys.go @@ -119,11 +119,15 @@ func (cc *CosmosProvider) KeyAddOrRestore(keyName string, coinType uint32, signi } } + done := SetSDKConfigContext(cc.PCfg.AccountPrefix) + info, err := cc.Keybase.NewAccount(keyName, mnemonicStr, "", hd.CreateHDPath(coinType, 0, 0).String(), algo) if err != nil { return nil, err } + done() + acc, err := info.GetAddress() if err != nil { return nil, err @@ -251,6 +255,10 @@ func (cc *CosmosProvider) KeyFromKeyOrAddress(keyOrAddress string) (string, erro if err != nil { return "", err } + + done := SetSDKConfigContext(cc.PCfg.AccountPrefix) + defer done() + kr, err := cc.Keybase.KeyByAddress(acc) if err != nil { return "", err diff --git a/relayer/chains/cosmos/provider.go b/relayer/chains/cosmos/provider.go index a967aa785..5a7e10eda 100644 --- a/relayer/chains/cosmos/provider.go +++ b/relayer/chains/cosmos/provider.go @@ -62,7 +62,7 @@ type CosmosProviderConfig struct { MinLoopDuration time.Duration `json:"min-loop-duration" yaml:"min-loop-duration"` ExtensionOptions []provider.ExtensionOption `json:"extension-options" yaml:"extension-options"` - //If FeeGrantConfiguration is set, TXs submitted by the ChainClient will be signed by the FeeGrantees in a round-robin fashion by default. + // If FeeGrantConfiguration is set, TXs submitted by the ChainClient will be signed by the FeeGrantees in a round-robin fashion by default. FeeGrants *FeeGrantConfiguration `json:"feegrants" yaml:"feegrants"` } @@ -70,13 +70,15 @@ type CosmosProviderConfig struct { // Clients can use other signing keys by invoking 'tx.SendMsgsWith' and specifying the signing key. type FeeGrantConfiguration struct { GranteesWanted int `json:"num_grantees" yaml:"num_grantees"` - //Normally this is the default ChainClient key - GranterKey string `json:"granter" yaml:"granter"` - //List of keys (by name) that this FeeGranter manages + // Normally this is the default ChainClient key + GranterKeyOrAddr string `json:"granter" yaml:"granter"` + // Whether we control the granter private key (if not, someone else must authorize our feegrants) + IsExternalGranter bool `json:"external_granter" yaml:"external_granter"` + // List of keys (by name) that this FeeGranter manages ManagedGrantees []string `json:"grantees" yaml:"grantees"` - //Last checked on chain (0 means grants never checked and may not exist) + // Last checked on chain (0 means grants never checked and may not exist) BlockHeightVerified int64 `json:"block_last_verified" yaml:"block_last_verified"` - //Index of the last ManagedGrantee used as a TX signer + // Index of the last ManagedGrantee used as a TX signer GranteeLastSignerIndex int } @@ -115,7 +117,7 @@ func (pc CosmosProviderConfig) NewProvider(log *zap.Logger, homepath string, deb walletStateMap: map[string]*WalletState{}, // TODO: this is a bit of a hack, we should probably have a better way to inject modules - Cdc: MakeCodec(pc.Modules, pc.ExtraCodecs), + Cdc: MakeCodec(pc.Modules, pc.ExtraCodecs, pc.AccountPrefix, pc.AccountPrefix+"valoper"), } return cp, nil diff --git a/relayer/chains/cosmos/tx.go b/relayer/chains/cosmos/tx.go index 09979ebe7..f2bb0f9bb 100644 --- a/relayer/chains/cosmos/tx.go +++ b/relayer/chains/cosmos/tx.go @@ -164,7 +164,7 @@ func (cc *CosmosProvider) SendMessagesToMempool( asyncCtx context.Context, asyncCallbacks []func(*provider.RelayerTxResponse, error), ) error { - txSignerKey, feegranterKey, err := cc.buildSignerConfig(msgs) + txSignerKey, feegranterKeyOrAddr, err := cc.buildSignerConfig(msgs) if err != nil { return err } @@ -173,7 +173,7 @@ func (cc *CosmosProvider) SendMessagesToMempool( sequenceGuard.Mu.Lock() defer sequenceGuard.Mu.Unlock() - txBytes, sequence, fees, err := cc.buildMessages(ctx, msgs, memo, 0, txSignerKey, feegranterKey, sequenceGuard) + txBytes, sequence, fees, err := cc.buildMessages(ctx, msgs, memo, 0, txSignerKey, feegranterKeyOrAddr, sequenceGuard) if err != nil { // Account sequence mismatch errors can happen on the simulated transaction also. if strings.Contains(err.Error(), legacyerrors.ErrWrongSequence.Error()) { @@ -202,7 +202,6 @@ func (cc *CosmosProvider) SubmitTxAwaitResponse(ctx context.Context, msgs []sdk. return nil, err } - fmt.Printf("TX result code: %d. Waiting for TX with hash %s\n", resp.Code, resp.Hash) tx1resp, err := cc.AwaitTx(bytes.HexBytes(resp.Hash), 15*time.Second) if err != nil { return nil, err @@ -273,9 +272,9 @@ func (cc *CosmosProvider) SendMsgsWith(ctx context.Context, msgs []sdk.Msg, memo } } - //Cannot feegrant your own TX + // Cannot feegrant your own TX if signingKey != feegranterKey && feegranterKey != "" { - //Must be set in Factory to affect gas calculation (sim tx) as well as real tx + // Must be set in Factory to affect gas calculation (sim tx) as well as real tx txf = txf.WithFeeGranter(feegrantKeyAcc) } @@ -542,14 +541,14 @@ func parseEventsFromTxResponse(resp *sdk.TxResponse) []provider.RelayerEvent { func (cc *CosmosProvider) buildSignerConfig(msgs []provider.RelayerMessage) ( txSignerKey string, - feegranterKey string, + feegranterKeyOrAddr string, err error, ) { - //Guard against race conditions when choosing a signer/feegranter + // Guard against race conditions when choosing a signer/feegranter cc.feegrantMu.Lock() defer cc.feegrantMu.Unlock() - //Some messages have feegranting disabled. If any message in the TX disables feegrants, then the TX will not be feegranted. + // Some messages have feegranting disabled. If any message in the TX disables feegrants, then the TX will not be feegranted. isFeegrantEligible := cc.PCfg.FeeGrants != nil for _, curr := range msgs { @@ -560,11 +559,11 @@ func (cc *CosmosProvider) buildSignerConfig(msgs []provider.RelayerMessage) ( } } - //By default, we should sign TXs with the provider's default key + // By default, we should sign TXs with the provider's default key txSignerKey = cc.PCfg.Key if isFeegrantEligible { - txSignerKey, feegranterKey = cc.GetTxFeeGrant() + txSignerKey, feegranterKeyOrAddr = cc.GetTxFeeGrant() signerAcc, addrErr := cc.GetKeyAddressForKey(txSignerKey) if addrErr != nil { err = addrErr @@ -577,7 +576,7 @@ func (cc *CosmosProvider) buildSignerConfig(msgs []provider.RelayerMessage) ( return } - //Overwrite the 'Signer' field in any Msgs that provide an 'optionalSetSigner' callback + // Overwrite the 'Signer' field in any Msgs that provide an 'optionalSetSigner' callback for _, curr := range msgs { if cMsg, ok := curr.(CosmosMessage); ok { if cMsg.SetSigner != nil { @@ -596,7 +595,7 @@ func (cc *CosmosProvider) buildMessages( memo string, gas uint64, txSignerKey string, - feegranterKey string, + feegranterKeyOrAddr string, sequenceGuard *WalletState, ) ( txBytes []byte, @@ -625,11 +624,19 @@ func (cc *CosmosProvider) buildMessages( txf = txf.WithSequence(sequence) } - //Cannot feegrant your own TX - if txSignerKey != feegranterKey && feegranterKey != "" { - granterAddr, err := cc.GetKeyAddressForKey(feegranterKey) - if err != nil { - return nil, 0, sdk.Coins{}, err + // Cannot feegrant your own TX + if txSignerKey != feegranterKeyOrAddr && feegranterKeyOrAddr != "" { + var granterAddr sdk.AccAddress + if cc.PCfg.FeeGrants != nil && cc.PCfg.FeeGrants.IsExternalGranter { + granterAddr, err = cc.DecodeBech32AccAddr(feegranterKeyOrAddr) + if err != nil { + return nil, 0, sdk.Coins{}, err + } + } else { + granterAddr, err = cc.GetKeyAddressForKey(feegranterKeyOrAddr) + if err != nil { + return nil, 0, sdk.Coins{}, err + } } txf = txf.WithFeeGranter(granterAddr)