Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Merge PR #55: Updated Provider implementation
Browse files Browse the repository at this point in the history
* make changes to reflect new provider api and add dynamic trusting period retrieval

* debugging

* debugging

* debugging

* debugging

* debugging

* debugging

* debugging

* test a possible fix?

* test a possible fix?

* remove debug output

* init modules on chain client properly and better keyring building

* init keybase in Init()
  • Loading branch information
jtieri authored Jan 10, 2022
1 parent 65fa5fc commit dc50c1d
Show file tree
Hide file tree
Showing 11 changed files with 168 additions and 54 deletions.
23 changes: 15 additions & 8 deletions client/chain_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
"path"
"time"

"github.com/cosmos/cosmos-sdk/crypto/keyring"
Expand Down Expand Up @@ -33,15 +34,9 @@ type ChainClient struct {
Logger log.Logger
}

func NewChainClient(ccc *ChainClientConfig, input io.Reader, output io.Writer, kro ...keyring.Option) (*ChainClient, error) {
// TODO: test key directory and return error if not created
keybase, err := keyring.New(ccc.ChainID, ccc.KeyringBackend, ccc.KeyDirectory, input, kro...)
if err != nil {
return nil, err
}
// TODO: figure out how to deal with input or maybe just make all keyring backends test?
func NewChainClient(ccc *ChainClientConfig, homepath string, input io.Reader, output io.Writer, kro ...keyring.Option) (*ChainClient, error) {
ccc.KeyDirectory = keysDir(homepath, ccc.ChainID)
cc := &ChainClient{
Keybase: keybase,
KeyringOptions: kro,
Config: ccc,
Input: input,
Expand All @@ -56,6 +51,13 @@ func NewChainClient(ccc *ChainClientConfig, input io.Reader, output io.Writer, k
}

func (cc *ChainClient) Init() error {
// TODO: test key directory and return error if not created
keybase, err := keyring.New(cc.Config.ChainID, cc.Config.KeyringBackend, cc.Config.KeyDirectory, cc.Input, cc.KeyringOptions...)
if err != nil {
return err
}
// TODO: figure out how to deal with input or maybe just make all keyring backends test?

timeout, _ := time.ParseDuration(cc.Config.Timeout)
rpcClient, err := NewRPCClient(cc.Config.RPCAddr, timeout)
if err != nil {
Expand All @@ -69,6 +71,7 @@ func (cc *ChainClient) Init() error {

cc.RPCClient = rpcClient
cc.LightProvider = lightprovider
cc.Keybase = keybase

return nil
}
Expand Down Expand Up @@ -176,3 +179,7 @@ func (cc *ChainClient) AccountFromKeyOrAddress(keyOrAddress string) (out sdk.Acc
}
return
}

func keysDir(home, chainID string) string {
return path.Join(home, "keys", chainID)
}
52 changes: 45 additions & 7 deletions client/config.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,54 @@
package client

import (
"github.com/cosmos/relayer/v2/relayer/provider"
"github.com/cosmos/cosmos-sdk/x/auth"
authz "github.com/cosmos/cosmos-sdk/x/authz/module"
"github.com/cosmos/cosmos-sdk/x/bank"
"github.com/cosmos/cosmos-sdk/x/capability"
"github.com/cosmos/cosmos-sdk/x/crisis"
"github.com/cosmos/cosmos-sdk/x/distribution"
distrclient "github.com/cosmos/cosmos-sdk/x/distribution/client"
feegrant "github.com/cosmos/cosmos-sdk/x/feegrant/module"
"github.com/cosmos/cosmos-sdk/x/gov"
"github.com/cosmos/cosmos-sdk/x/mint"
"github.com/cosmos/cosmos-sdk/x/params"
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/cosmos-sdk/x/upgrade"
upgradeclient "github.com/cosmos/cosmos-sdk/x/upgrade/client"
"github.com/cosmos/ibc-go/v2/modules/apps/transfer"
ibc "github.com/cosmos/ibc-go/v2/modules/core"
"os"
"time"

"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/relayer/relayer/provider"
)

var (
_ provider.ProviderConfig = &ChainClientConfig{}
_ provider.ProviderConfig = &ChainClientConfig{}
ModuleBasics = []module.AppModuleBasic{
auth.AppModuleBasic{},
authz.AppModuleBasic{},
bank.AppModuleBasic{},
capability.AppModuleBasic{},
// TODO: add osmosis governance proposal types here
// TODO: add other proposal types here
gov.NewAppModuleBasic(
paramsclient.ProposalHandler, distrclient.ProposalHandler, upgradeclient.ProposalHandler, upgradeclient.CancelProposalHandler,
),
crisis.AppModuleBasic{},
distribution.AppModuleBasic{},
feegrant.AppModuleBasic{},
mint.AppModuleBasic{},
params.AppModuleBasic{},
slashing.AppModuleBasic{},
staking.AppModuleBasic{},
upgrade.AppModuleBasic{},
transfer.AppModuleBasic{},
ibc.AppModuleBasic{},
}
)

type ChainClientConfig struct {
Expand All @@ -21,7 +60,6 @@ type ChainClientConfig struct {
KeyringBackend string `json:"keyring-backend" yaml:"keyring-backend"`
GasAdjustment float64 `json:"gas-adjustment" yaml:"gas-adjustment"`
GasPrices string `json:"gas-prices" yaml:"gas-prices"`
TrustingPeriod string `json:"omitempty" yaml:"omitempty"`
KeyDirectory string `json:"key-directory" yaml:"key-directory"`
Debug bool `json:"debug" yaml:"debug"`
Timeout string `json:"timeout" yaml:"timeout"`
Expand All @@ -34,7 +72,8 @@ func (ccc *ChainClientConfig) NewProvider(homepath string, debug bool) (provider
if err := ccc.Validate(); err != nil {
return nil, err
}
p, err := NewChainClient(ccc, os.Stdin, os.Stdout)
ccc.Modules = append([]module.AppModuleBasic{}, ModuleBasics...)
p, err := NewChainClient(ccc, homepath, os.Stdin, os.Stdout)
if err != nil {
return nil, err
}
Expand All @@ -58,7 +97,6 @@ func GetCosmosHubConfig(keyHome string, debug bool) *ChainClientConfig {
KeyringBackend: "test",
GasAdjustment: 1.2,
GasPrices: "0.01uatom",
TrustingPeriod: "336h",
KeyDirectory: keyHome,
Debug: debug,
Timeout: "20s",
Expand All @@ -77,7 +115,6 @@ func GetOsmosisConfig(keyHome string, debug bool) *ChainClientConfig {
KeyringBackend: "test",
GasAdjustment: 1.2,
GasPrices: "0.01uosmo",
TrustingPeriod: "300h",
KeyDirectory: keyHome,
Debug: debug,
Timeout: "20s",
Expand All @@ -87,6 +124,7 @@ func GetOsmosisConfig(keyHome string, debug bool) *ChainClientConfig {
}

func GetTestClient() *ChainClient {
cl, _ := NewChainClient(GetCosmosHubConfig("/tmp", true), nil, nil)
homepath := "/tmp"
cl, _ := NewChainClient(GetCosmosHubConfig(homepath, true), homepath, nil, nil)
return cl
}
2 changes: 1 addition & 1 deletion client/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package client

import (
"errors"
"github.com/cosmos/relayer/v2/relayer/provider"
"os"

ckeys "github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/crypto/hd"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/go-bip39"
"github.com/cosmos/relayer/relayer/provider"
)

func (cc *ChainClient) CreateKeystore(path string) error {
Expand Down
57 changes: 33 additions & 24 deletions client/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import (
"context"
"errors"
"fmt"
"math"
"reflect"
"strconv"
"time"

"github.com/gogo/protobuf/proto"

"github.com/avast/retry-go"
"github.com/cosmos/cosmos-sdk/codec"
codectypes "github.com/cosmos/cosmos-sdk/codec/types"
Expand All @@ -21,7 +24,7 @@ import (
host "github.com/cosmos/ibc-go/v2/modules/core/24-host"
ibcexported "github.com/cosmos/ibc-go/v2/modules/core/exported"
tmclient "github.com/cosmos/ibc-go/v2/modules/light-clients/07-tendermint/types"
"github.com/cosmos/relayer/v2/relayer/provider"
"github.com/cosmos/relayer/relayer/provider"
ctypes "github.com/tendermint/tendermint/rpc/core/types"
tmtypes "github.com/tendermint/tendermint/types"
)
Expand Down Expand Up @@ -83,6 +86,10 @@ func (cm CosmosMessage) Type() string {
return sdk.MsgTypeURL(cm.Msg)
}

func (cm CosmosMessage) MsgBytes() ([]byte, error) {
return proto.Marshal(cm.Msg)
}

func (cc *ChainClient) ProviderConfig() provider.ProviderConfig {
return cc.Config
}
Expand All @@ -104,21 +111,29 @@ func (cc *ChainClient) Timeout() string {
}

// Address returns the chains configured address as a string
// NOTE: we are returning an empty string when there are errors right now so the return value
// needs to be checked before being used anywhere Address is called
func (cc *ChainClient) Address() string {
func (cc *ChainClient) Address() (string, error) {
var (
acc sdk.AccAddress
err error
)
if acc, err = cc.GetKeyAddress(); err != nil {
return ""
return "", err
}
return acc.String()
return acc.String(), nil
}

func (cc *ChainClient) TrustingPeriod() string {
return cc.Config.TrustingPeriod
func (cc *ChainClient) TrustingPeriod() (time.Duration, error) {
res, err := cc.QueryStakingParams(context.Background())
if err != nil {
return 0, err
}
integer, _ := math.Modf(res.UnbondingTime.Hours() * 0.7)
trustingStr := fmt.Sprintf("%vh", integer)
tp, err := time.ParseDuration(trustingStr)
if err != nil {
return 0, nil
}
return tp, nil
}

// CreateClient creates an sdk.Msg to update the client on src with consensus state from dst
Expand Down Expand Up @@ -454,22 +469,19 @@ func (cc *ChainClient) ChannelOpenConfirm(dstQueryProvider provider.QueryProvide
return []provider.RelayerMessage{updateMsg, NewCosmosMessage(msg)}, msg.ValidateBasic()
}

func (cc *ChainClient) ChannelCloseInit(srcPortId, srcChanId string) provider.RelayerMessage {
func (cc *ChainClient) ChannelCloseInit(srcPortId, srcChanId string) (provider.RelayerMessage, error) {
var (
acc sdk.AccAddress
err error
)
if acc, err = cc.GetKeyAddress(); err != nil {
// TODO ChannelCloseInit should really also return an error instead of printing this line
// Change this on the Provider interface in the relayer & come back
fmt.Printf("Error getting key address in ChannelCloseInit. Err: %s\n", err.Error())
return nil
return nil, err
}
return NewCosmosMessage(chantypes.NewMsgChannelCloseInit(
srcPortId,
srcChanId,
acc.String(),
))
)), nil
}

func (cc *ChainClient) ChannelCloseConfirm(dstQueryProvider provider.QueryProvider, dsth int64, dstChanId, dstPortId, srcPortId, srcChanId string) (provider.RelayerMessage, error) {
Expand Down Expand Up @@ -622,16 +634,15 @@ func (cc *ChainClient) MsgRelayAcknowledgement(dst provider.ChainProvider, dstCh
}

// MsgTransfer creates a new transfer message
func (cc *ChainClient) MsgTransfer(amount sdk.Coin, dstChainId, dstAddr, srcPortId, srcChanId string, timeoutHeight, timeoutTimestamp uint64) provider.RelayerMessage {
func (cc *ChainClient) MsgTransfer(amount sdk.Coin, dstChainId, dstAddr, srcPortId, srcChanId string, timeoutHeight, timeoutTimestamp uint64) (provider.RelayerMessage, error) {
var (
acc sdk.AccAddress
err error
)
if acc, err = cc.GetKeyAddress(); err != nil {
// TODO should really be returning an error here
fmt.Printf("Error getting key address in MsgTransfer. Err: %s\n", err.Error())
return nil
return nil, err
}

version := clienttypes.ParseChainID(dstChainId)
return NewCosmosMessage(transfertypes.NewMsgTransfer(
srcPortId,
Expand All @@ -641,7 +652,7 @@ func (cc *ChainClient) MsgTransfer(amount sdk.Coin, dstChainId, dstAddr, srcPort
dstAddr,
clienttypes.NewHeight(version, timeoutHeight),
timeoutTimestamp,
))
)), nil
}

// MsgRelayTimeout constructs the MsgTimeout which is to be sent to the sending chain.
Expand Down Expand Up @@ -970,19 +981,17 @@ func acknowledgementsFromResultTx(dstChanId, dstPortId, srcChanId, srcPortId str
return nil, fmt.Errorf("no packet data found")
}

func (cc *ChainClient) MsgUpgradeClient(srcClientId string, consRes *clienttypes.QueryConsensusStateResponse, clientRes *clienttypes.QueryClientStateResponse) provider.RelayerMessage {
func (cc *ChainClient) MsgUpgradeClient(srcClientId string, consRes *clienttypes.QueryConsensusStateResponse, clientRes *clienttypes.QueryClientStateResponse) (provider.RelayerMessage, error) {
var (
acc sdk.AccAddress
err error
)
if acc, err = cc.GetKeyAddress(); err != nil {
// TODO should really be returning an error here
fmt.Printf("Error getting key address in MsgUpgradeClient. Err: %s\n", err.Error())
return nil
return nil, err
}
return NewCosmosMessage(&clienttypes.MsgUpgradeClient{ClientId: srcClientId, ClientState: clientRes.ClientState,
ConsensusState: consRes.ConsensusState, ProofUpgradeClient: consRes.GetProof(),
ProofUpgradeConsensusState: consRes.ConsensusState.Value, Signer: acc.String()})
ProofUpgradeConsensusState: consRes.ConsensusState.Value, Signer: acc.String()}), nil
}

// AutoUpdateClient update client automatically to prevent expiry
Expand Down
15 changes: 15 additions & 0 deletions client/provider_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package client

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
)

func TestGetTrustingPeriod(t *testing.T) {
hubClient := GetTestClient()
tp, err := hubClient.TrustingPeriod()
fmt.Println(tp)
require.NoError(t, err)
}
8 changes: 8 additions & 0 deletions client/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -962,6 +962,14 @@ func (cc *ChainClient) QueryDenomsMetadata(ctx context.Context, pageReq *query.P
return bankTypes.NewQueryClient(cc).DenomsMetadata(ctx, &bankTypes.QueryDenomsMetadataRequest{Pagination: pageReq})
}

func (cc *ChainClient) QueryStakingParams(ctx context.Context) (*stakingtypes.Params, error) {
res, err := stakingtypes.NewQueryClient(cc).Params(ctx, &stakingtypes.QueryParamsRequest{})
if err != nil {
return nil, err
}
return &res.Params, nil
}

func DefaultPageRequest() *querytypes.PageRequest {
return &querytypes.PageRequest{
Key: []byte(""),
Expand Down
Loading

0 comments on commit dc50c1d

Please sign in to comment.