From 4558cf8039c6f13ffd320978933466e40f18faa3 Mon Sep 17 00:00:00 2001 From: Marko Baricevic Date: Sat, 23 May 2020 15:40:53 +0200 Subject: [PATCH 01/17] add linting and bring linting to ci --- .github/workflows/build.yml | 94 ++++++++++++++++++------------------- .golangci.yml | 61 ++++++++++++++++++++++++ Makefile | 2 +- cmd/chains.go | 28 ++++++----- cmd/config.go | 21 +++++---- cmd/dev.go | 21 ++++++--- cmd/flags.go | 2 +- cmd/lite.go | 4 +- cmd/paths.go | 38 ++++++++------- cmd/query.go | 7 +-- cmd/raw.go | 47 +++++++++++++------ cmd/start.go | 2 +- cmd/strategy.go | 3 +- cmd/testnets.go | 2 +- cmd/tx.go | 13 +++-- cmd/xfer.go | 8 ++-- relayer/chain.go | 19 ++++---- relayer/faucet.go | 5 +- relayer/ics24.go | 31 ++++++------ relayer/log-tx.go | 9 ++-- relayer/naive-strategy.go | 22 +++++---- relayer/packet-tx.go | 5 +- relayer/path.go | 6 ++- relayer/pathEnd.go | 37 ++++++++++----- relayer/query.go | 33 +++++++------ relayer/relayMsgs.go | 12 +++-- relayer/relayPackets.go | 11 +++-- relayer/strategies.go | 13 ++--- relayer/verifier.go | 10 ++-- test/relayer_coco_test.go | 35 +++++++------- test/test_chains.go | 7 +-- test/test_queries.go | 16 +++---- test/test_setup.go | 41 +++++++++------- 33 files changed, 406 insertions(+), 259 deletions(-) create mode 100644 .golangci.yml diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 45ce53530..0deb8fd0c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,55 +1,55 @@ -name: BUILD - lint, build and binary upload +name: BUILD - build and binary upload on: [push] jobs: - build: name: build runs-on: ubuntu-latest steps: - - # Install and setup go - - name: Set up Go 1.14 - uses: actions/setup-go@v1 - with: - go-version: 1.14 - id: go - - # setup gopath - - name: Set PATH - run: | - echo "::set-env name=GOPATH::$(go env GOPATH)" - echo "::add-path::$(go env GOPATH)/bin" - shell: bash - - # # install linter - # - name: install linter - # run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $GOPATH/bin v1.24.0 - - # checkout relayer - - name: checkout relayer - uses: actions/checkout@v2 - - # setup cache - - uses: actions/cache@v1 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - # # run linter - # - name: linter - # run: make ci-lint - - # build binary - - name: build binary and move to upload location - run: make build - - # upload resulting binaries - - name: upload binaries - uses: actions/upload-artifact@v1 - with: - name: rly - path: ./build/rly + # Install and setup go + - name: Set up Go 1.14 + uses: actions/setup-go@v2 + with: + go-version: 1.14 + + # setup gopath + - name: Set PATH + run: | + echo "::add-path::$(go env GOPATH)/bin" + shell: bash + + # checkout relayer + - name: checkout relayer + uses: actions/checkout@v2 + + # setup cache + - uses: actions/cache@v1 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + # build binary + - name: build binary and move to upload location + run: make build + + # upload resulting binaries + - name: upload binaries + uses: actions/upload-artifact@v1 + with: + name: rly + path: ./build/rly + + golangci: + name: golangci-lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: golangci/golangci-lint-action@master + with: + # Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version. + version: v1.27 + args: --timeout 10m + github-token: ${{ secrets.github_token }} diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..b33694958 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,61 @@ +linters: + enable: + - bodyclose + - deadcode + - depguard + - dogsled + # - errcheck + # - funlen + # - gochecknoglobals + # - gochecknoinits + - goconst + - gocritic + # - gocyclo + # - godox + - gofmt + - goimports + - golint + - gosec + - gosimple + - govet + - ineffassign + - interfacer + - lll + - misspell + # - maligned + - nakedret + - prealloc + - scopelint + - staticcheck + - structcheck + - stylecheck + - typecheck + - unconvert + # - unparam + - unused + - varcheck + # - whitespace + # - wsl + # - gocognit + - nolintlint + +issues: + exclude-rules: + - linters: + - lll + source: "https://" + max-same-issues: 50 + +linters-settings: + dogsled: + max-blank-identifiers: 3 + maligned: + suggest-new: true + # govet: + # check-shadowing: true + golint: + min-confidence: 0 + # gocyclo: + # min-complexity: 10 + # misspell: + # locale: US diff --git a/Makefile b/Makefile index 99980348e..513df3a81 100644 --- a/Makefile +++ b/Makefile @@ -60,7 +60,7 @@ coverage: @echo "viewing test coverage..." @go tool cover --html=coverage.out -ci-lint: +lint: @GO111MODULE=on golangci-lint run @find . -name '*.go' -type f -not -path "*.git*" | xargs gofmt -d -s @go mod verify diff --git a/cmd/chains.go b/cmd/chains.go index f72fc2f67..28512cefc 100644 --- a/cmd/chains.go +++ b/cmd/chains.go @@ -15,6 +15,11 @@ import ( "github.com/iqlusioninc/relayer/relayer" ) +const ( + check = "✔" + xIcon = "✘" +) + func chainsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "chains", @@ -55,7 +60,7 @@ func chainsAddrCmd() *cobra.Command { return err } - fmt.Println(string(addr.String())) + fmt.Println(addr.String()) return nil }, } @@ -192,29 +197,29 @@ func chainsListCmd() *cobra.Command { default: for i, c := range config.Chains { var ( - lite = "✘" - key = "✘" - path = "✘" - bal = "✘" + lite = xIcon + key = xIcon + path = xIcon + bal = xIcon ) _, err := c.GetAddress() if err == nil { - key = "✔" + key = check } coins, err := c.QueryBalance(c.Key) if err == nil && !coins.Empty() { - bal = "✔" + bal = check } _, err = c.GetLatestLiteHeader() if err == nil { - lite = "✔" + lite = check } for _, pth := range config.Paths { if pth.Src.ChainID == c.ChainID || pth.Dst.ChainID == c.ChainID { - path = "✔" + path = check } } fmt.Printf("%2d: %-20s -> key(%s) bal(%s) lite(%s) path(%s)\n", i, c.ChainID, key, bal, lite, path) @@ -269,7 +274,8 @@ func chainsAddDirCmd() *cobra.Command { cmd := &cobra.Command{ Use: "add-dir [dir]", Aliases: []string{"ad"}, - Short: "Add new chains to the configuration file from a directory full of chain configuration, useful for adding testnet configurations", + Short: `Add new chains to the configuration file from a directory + full of chain configuration, useful for adding testnet configurations`, RunE: func(cmd *cobra.Command, args []string) (err error) { var out *Config if out, err = filesAdd(args[0]); err != nil { @@ -432,7 +438,7 @@ func userInputAdd(cmd *cobra.Command) (cfg *Config, err error) { func urlInputAdd(rawurl string) (cfg *Config, err error) { u, err := url.Parse(rawurl) if err != nil || u.Scheme == "" || u.Host == "" { - return cfg, errors.New("Invalid URL") + return cfg, errors.New("invalid URL") } resp, err := http.Get(u.String()) diff --git a/cmd/config.go b/cmd/config.go index 81e651792..5c90a21bb 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -31,6 +31,8 @@ import ( "gopkg.in/yaml.v2" ) +const ORDERED = "ORDERED" + func configCmd() *cobra.Command { cmd := &cobra.Command{ Use: "config", @@ -62,9 +64,9 @@ func configShowCmd() *cobra.Command { cfgPath := path.Join(home, "config", "config.yaml") if _, err := os.Stat(cfgPath); os.IsNotExist(err) { if _, err := os.Stat(home); os.IsNotExist(err) { - return fmt.Errorf("Home path does not exist: %s", home) + return fmt.Errorf("home path does not exist: %s", home) } - return fmt.Errorf("Config does not exist: %s", cfgPath) + return fmt.Errorf("config does not exist: %s", cfgPath) } out, err := yaml.Marshal(config) @@ -129,7 +131,7 @@ func configInitCmd() *cobra.Command { } // Otherwise, the config file exists, and an error is returned... - return fmt.Errorf("Config already exists: %s", cfgPath) + return fmt.Errorf("config already exists: %s", cfgPath) }, } return cmd @@ -139,7 +141,8 @@ func configAddDirCmd() *cobra.Command { cmd := &cobra.Command{ Use: "add-dir [dir]", Aliases: []string{"ad"}, - Short: "Add new chains and paths to the configuration file from a directory full of chain and path configuration, useful for adding testnet configurations", + Short: `Add new chains and paths to the configuration file from a + directory full of chain and path configuration, useful for adding testnet configurations`, RunE: func(cmd *cobra.Command, args []string) (err error) { var out *Config if out, err = cfgFilesAdd(args[0]); err != nil { @@ -185,8 +188,8 @@ func cfgFilesAdd(dir string) (cfg *Config, err error) { // In the case that order isn't added to the path, add it manually if p.Src.Order == "" || p.Dst.Order == "" { - p.Src.Order = "ORDERED" - p.Dst.Order = "ORDERED" + p.Src.Order = ORDERED + p.Dst.Order = ORDERED } pthName := strings.Split(f.Name(), ".")[0] @@ -305,12 +308,12 @@ func (c *Config) DeleteChain(chain string) *Config { func validateConfig(c *Config) error { to, err := time.ParseDuration(config.Global.Timeout) if err != nil { - return fmt.Errorf("Did you remember to run 'rly config init' error:%w", err) + return fmt.Errorf("did you remember to run 'rly config init' error:%w", err) } for _, i := range c.Chains { if err := i.Init(homePath, appCodec, cdc, to, debug); err != nil { - return fmt.Errorf("Did you remember to run 'rly config init' error:%w", err) + return fmt.Errorf("did you remember to run 'rly config init' error:%w", err) } } @@ -377,7 +380,7 @@ func overWriteConfig(cmd *cobra.Command, cfg *Config) error { } // overwrite the config file - err = ioutil.WriteFile(viper.ConfigFileUsed(), out, 0666) + err = ioutil.WriteFile(viper.ConfigFileUsed(), out, 0600) if err != nil { return err } diff --git a/cmd/dev.go b/cmd/dev.go index c4a2390b7..b961f4ab3 100644 --- a/cmd/dev.go +++ b/cmd/dev.go @@ -55,7 +55,9 @@ func gozCSVCmd() *cobra.Command { info := to[c.ChainID] if info != nil { c.TeamInfo = info - w.Write([]string{c.TeamInfo.Name, c.TeamInfo.Address, c.TeamInfo.RPCAddr, c.ClientID}) + if err := w.Write([]string{c.TeamInfo.Name, c.TeamInfo.Address, c.TeamInfo.RPCAddr, c.ClientID}); err != nil { + return err + } } } w.Flush() @@ -167,7 +169,7 @@ func listenCmd() *cobra.Command { } if block && tx { - return fmt.Errorf("Must output block and/or tx") + return fmt.Errorf("must output block and/or tx") } done := c.ListenRPCEmitJSON(tx, block, data) @@ -289,20 +291,22 @@ func rlyService() *cobra.Command { if srcBal, err = chains[src].QueryBalance(chains[src].Key); err != nil { return err } else if srcBal.AmountOf(chains[src].DefaultDenom).IsZero() { - return fmt.Errorf("no balance on %s, ensure %s has a balance before continuing setup", src, chains[src].MustGetAddress()) + return fmt.Errorf("no balance on %s, ensure %s has a balance before continuing setup", + src, chains[src].MustGetAddress()) } if dstBal, err = chains[dst].QueryBalance(chains[dst].Key); err != nil { return err } else if dstBal.AmountOf(chains[dst].DefaultDenom).IsZero() { - return fmt.Errorf("no balance on %s, ensure %s has a balance before continuing setup", dst, chains[dst].MustGetAddress()) + return fmt.Errorf("no balance on %s, ensure %s has a balance before continuing setup", + dst, chains[dst].MustGetAddress()) } // ensure lite clients are initialized if _, err = chains[src].GetLatestLiteHeight(); err != nil { - return fmt.Errorf("no lite client on %s, ensure it is initalized before continuing: %w", src, err) + return fmt.Errorf("no lite client on %s, ensure it is initialized before continuing: %w", src, err) } if _, err = chains[dst].GetLatestLiteHeight(); err != nil { - return fmt.Errorf("no lite client on %s, ensure it is initalized before continuing: %w", dst, err) + return fmt.Errorf("no lite client on %s, ensure it is initialized before continuing: %w", dst, err) } fmt.Printf(`[Unit] @@ -442,5 +446,8 @@ func (cd *clientData) StatsD(cl *statsd.Client, prefix string) { fmt.Fprintf(os.Stderr, "%s", string(byt)) // TODO: add more cases here } - cl.TimeInMilliseconds(fmt.Sprintf("relayer.%s.client", prefix), float64(time.Since(cd.TimeOfLastUpdate).Milliseconds()), []string{"teamname", cd.TeamInfo.Name, "chain-id", cd.ChainID, "client-id", cd.ClientID, "connection-id", cd.ConnectionIDs[0], "channelid", cd.ChannelIDs[0]}, 1) + cl.TimeInMilliseconds(fmt.Sprintf("relayer.%s.client", prefix), //nolint:errcheck // ignore error + float64(time.Since(cd.TimeOfLastUpdate).Milliseconds()), + []string{"teamname", cd.TeamInfo.Name, "chain-id", cd.ChainID, + "client-id", cd.ClientID, "connection-id", cd.ConnectionIDs[0], "channelid", cd.ChannelIDs[0]}, 1) } diff --git a/cmd/flags.go b/cmd/flags.go index b1aae36fe..82b7f22f0 100644 --- a/cmd/flags.go +++ b/cmd/flags.go @@ -143,7 +143,7 @@ func timeoutFlag(cmd *cobra.Command) *cobra.Command { } func forceFlag(cmd *cobra.Command) *cobra.Command { - cmd.Flags().BoolP(flagForce, "f", false, "option to force non-standard behavior such as initialization of lite client from configured chain or generation of new path") + cmd.Flags().BoolP(flagForce, "f", false, "option to force non-standard behavior such as initialization of lite client from configured chain or generation of new path") //nolint:lll if err := viper.BindPFlag(flagForce, cmd.Flags().Lookup(flagForce)); err != nil { panic(err) } diff --git a/cmd/lite.go b/cmd/lite.go index 767f6daea..0fa8581c7 100644 --- a/cmd/lite.go +++ b/cmd/lite.go @@ -55,7 +55,7 @@ func initLiteCmd() *cobra.Command { Long: `Initiate the light client by: 1. passing it a root of trust as a --hash/-x and --height 2. via --url/-u where trust options can be found - 3. Use --force/-f to initalize from the configured node`, + 3. Use --force/-f to initialize from the configured node`, Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { chain, err := config.Chains.Get(args[0]) @@ -289,7 +289,7 @@ func deleteLiteCmd() *cobra.Command { func queryTrustOptions(url string) (out lite.TrustOptions, err error) { // fetch from URL - res, err := http.Get(url) + res, err := http.Get(url) //nolint:gosec // Potential HTTP request made with variable url if err != nil { return } diff --git a/cmd/paths.go b/cmd/paths.go index 155abef37..caf7f77a3 100644 --- a/cmd/paths.go +++ b/cmd/paths.go @@ -3,10 +3,11 @@ package cmd import ( "encoding/json" "fmt" - "github.com/tendermint/tendermint/types/time" "io/ioutil" "os" + "github.com/tendermint/tendermint/types/time" + connTypes "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" chanTypes "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" tmclient "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/types" @@ -16,6 +17,8 @@ import ( "gopkg.in/yaml.v2" ) +const OPEN = "OPEN" + func pathsCmd() *cobra.Command { cmd := &cobra.Command{ Use: "paths", @@ -121,7 +124,7 @@ func pathsGenCmd() *cobra.Command { clnt, ok := c.(tmclient.ClientState) if ok && clnt.LastHeader.Commit != nil && clnt.LastHeader.Header != nil { if clnt.GetChainID() == dst && !clnt.IsFrozen() && - time.Now().Sub(clnt.GetLatestTimestamp()) < clnt.TrustingPeriod{ + time.Now().Sub(clnt.GetLatestTimestamp()) < clnt.TrustingPeriod { path.Src.ClientID = clnt.GetID() } } @@ -210,8 +213,8 @@ func pathsGenCmd() *cobra.Command { // we should generate a new connection identifier dstCpForSrc := srcCon.Counterparty.ConnectionID == dstCon.ID srcCpForDst := dstCon.Counterparty.ConnectionID == srcCon.ID - srcOpen := srcCon.State.String() == "OPEN" - dstOpen := dstCon.State.String() == "OPEN" + srcOpen := srcCon.State.String() == OPEN + dstOpen := dstCon.State.String() == OPEN if !(dstCpForSrc && srcCpForDst && srcOpen && dstOpen) { path.Src.ConnectionID = relayer.RandLowerCaseLetterString(10) path.Dst.ConnectionID = relayer.RandLowerCaseLetterString(10) @@ -263,8 +266,8 @@ func pathsGenCmd() *cobra.Command { case path.Src.ChannelID != "" && path.Dst.ChannelID != "": dstCpForSrc := srcChan.Counterparty.ChannelID == dstChan.ID srcCpForDst := dstChan.Counterparty.ChannelID == srcChan.ID - srcOpen := srcChan.State.String() == "OPEN" - dstOpen := dstChan.State.String() == "OPEN" + srcOpen := srcChan.State.String() == OPEN + dstOpen := dstChan.State.String() == OPEN srcPort := srcChan.PortID == path.Src.PortID dstPort := dstChan.PortID == path.Dst.PortID srcOrder := srcChan.Ordering.String() == path.Src.Order @@ -344,15 +347,15 @@ func pathsListCmd() *cobra.Command { for k, pth := range config.Paths { // TODO: replace this with relayer.QueryPathStatus var ( - chains = "✘" - clients = "✘" - connection = "✘" - channel = "✘" + chains = xIcon + clients = xIcon + connection = xIcon + channel = xIcon ) src, dst := pth.Src.ChainID, pth.Dst.ChainID ch, err := config.Chains.Gets(src, dst) if err == nil { - chains = "✔" + chains = check err = ch[src].SetPath(pth.Src) if err != nil { printPath(i, k, pth, chains, clients, connection, channel) @@ -374,7 +377,7 @@ func pathsListCmd() *cobra.Command { srcCs, err := ch[src].QueryClientState() dstCs, _ := ch[dst].QueryClientState() if err == nil && srcCs != nil && dstCs != nil { - clients = "✔" + clients = check } else { printPath(i, k, pth, chains, clients, connection, channel) i++ @@ -392,7 +395,7 @@ func pathsListCmd() *cobra.Command { srcConn, err := ch[src].QueryConnection(srch) dstConn, _ := ch[dst].QueryConnection(dsth) if err == nil && srcConn.Connection.State == ibcTypes.OPEN && dstConn.Connection.State == ibcTypes.OPEN { - connection = "✔" + connection = check } else { printPath(i, k, pth, chains, clients, connection, channel) i++ @@ -402,7 +405,7 @@ func pathsListCmd() *cobra.Command { srcChan, err := ch[src].QueryChannel(srch) dstChan, _ := ch[dst].QueryChannel(dsth) if err == nil && srcChan.Channel.State == ibcTypes.OPEN && dstChan.Channel.State == ibcTypes.OPEN { - channel = "✔" + channel = check } else { printPath(i, k, pth, chains, clients, connection, channel) i++ @@ -438,9 +441,9 @@ type PathWithStatus struct { func checkmark(status bool) string { if status { - return "✔" + return check } - return "✘" + return xIcon } func pathsShowCmd() *cobra.Command { @@ -546,7 +549,8 @@ func pathsShowCmd() *cobra.Command { Clients: %s Connection: %s Channel: %s -`, args[0], path.Strategy.Type, path.Src.ChainID, path.Src.ClientID, path.Src.ConnectionID, path.Src.ChannelID, path.Src.PortID, +`, args[0], path.Strategy.Type, path.Src.ChainID, + path.Src.ClientID, path.Src.ConnectionID, path.Src.ChannelID, path.Src.PortID, path.Dst.ChainID, path.Dst.ClientID, path.Dst.ConnectionID, path.Dst.ChannelID, path.Dst.PortID, checkmark(chains), checkmark(clients), checkmark(connection), checkmark(channel)) } diff --git a/cmd/query.go b/cmd/query.go index cf2d13e8b..46e19ce71 100644 --- a/cmd/query.go +++ b/cmd/query.go @@ -20,7 +20,7 @@ func queryCmd() *cobra.Command { Use: "query", Aliases: []string{"q"}, Short: "IBC Query Commands", - Long: "Commands to query IBC primatives, and other useful data on configured chains.", + Long: "Commands to query IBC primitives, and other useful data on configured chains.", } cmd.AddCommand( @@ -76,8 +76,9 @@ func queryTxs() *cobra.Command { cmd := &cobra.Command{ Use: "txs [chain-id] [events]", Short: "Query transactions by the events they produce", - Long: strings.TrimSpace(`Search for transactions that match the exact given events where results are paginated. Each event -takes the form of '{eventType}.{eventAttribute}={value}' with multiple events seperated by '&'. + Long: strings.TrimSpace( + `Search for transactions that match the exact given events where results are paginated. Each event +takes the form of '{eventType}.{eventAttribute}={value}' with multiple events separated by '&'. Please refer to each module's documentation for the full set of events to query for. Each module documents its respective events under 'cosmos-sdk/x/{module}/spec/xx_events.md'.`), Args: cobra.ExactArgs(2), diff --git a/cmd/raw.go b/cmd/raw.go index f4823669d..a9bc5b730 100644 --- a/cmd/raw.go +++ b/cmd/raw.go @@ -1,6 +1,8 @@ package cmd import ( + "strings" + "github.com/cosmos/cosmos-sdk/client/flags" sdk "github.com/cosmos/cosmos-sdk/types" tmclient "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/types" @@ -76,7 +78,8 @@ func updateClientCmd() *cobra.Command { } } - return sendAndPrint([]sdk.Msg{chains[src].PathEnd.UpdateClient(dstHeader, chains[src].MustGetAddress())}, chains[src], cmd) + return sendAndPrint([]sdk.Msg{chains[src].PathEnd.UpdateClient(dstHeader, chains[src].MustGetAddress())}, + chains[src], cmd) }, } return heightFlag(cmd) @@ -104,7 +107,9 @@ func createClientCmd() *cobra.Command { return err } - return sendAndPrint([]sdk.Msg{chains[src].PathEnd.CreateClient(dstHeader, chains[dst].GetTrustingPeriod(), chains[src].MustGetAddress())}, chains[src], cmd) + return sendAndPrint([]sdk.Msg{chains[src].PathEnd.CreateClient(dstHeader, + chains[dst].GetTrustingPeriod(), chains[src].MustGetAddress())}, + chains[src], cmd) }, } return cmd @@ -130,7 +135,8 @@ func connInit() *cobra.Command { return err } - return sendAndPrint([]sdk.Msg{chains[src].PathEnd.ConnInit(chains[dst].PathEnd, chains[src].MustGetAddress())}, chains[src], cmd) + return sendAndPrint([]sdk.Msg{chains[src].PathEnd.ConnInit(chains[dst].PathEnd, chains[src].MustGetAddress())}, + chains[src], cmd) }, } return cmd @@ -183,7 +189,8 @@ func connTry() *cobra.Command { txs := []sdk.Msg{ chains[src].PathEnd.UpdateClient(hs[dst], chains[src].MustGetAddress()), - chains[src].PathEnd.ConnTry(chains[dst].PathEnd, dstConnState, dstConsState, dstCsHeight, chains[src].MustGetAddress()), + chains[src].PathEnd.ConnTry(chains[dst].PathEnd, dstConnState, + dstConsState, dstCsHeight, chains[src].MustGetAddress()), } return sendAndPrint(txs, chains[src], cmd) @@ -293,11 +300,13 @@ func connConfirm() *cobra.Command { func createConnectionStepCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "connection-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] [src-connection-id] [dst-connection-id]", + Use: strings.TrimSpace(`connection-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] + [src-connection-id] [dst-connection-id]`), Aliases: []string{"conn-step"}, Short: "create a connection between chains, passing in identifiers", - Long: "This command creates the next handshake message given a specifc set of identifiers. If the command fails, you can safely run it again to repair an unfinished connection", - Args: cobra.ExactArgs(6), + Long: strings.TrimSpace(`This command creates the next handshake message given a specifc set of identifiers. + If the command fails, you can safely run it again to repair an unfinished connection`), + Args: cobra.ExactArgs(6), RunE: func(cmd *cobra.Command, args []string) error { src, dst := args[0], args[1] chains, err := config.Chains.Gets(src, dst) @@ -336,7 +345,8 @@ func createConnectionStepCmd() *cobra.Command { func chanInit() *cobra.Command { cmd := &cobra.Command{ - Use: "chan-init [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] [src-conn-id] [dst-conn-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id] [ordering]", + Use: strings.TrimSpace(`chan-init [src-chain-id] [dst-chain-id] [src-client-id] + [dst-client-id] [src-conn-id] [dst-conn-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id] [ordering]`), Short: "chan-init", Args: cobra.ExactArgs(11), RunE: func(cmd *cobra.Command, args []string) error { @@ -354,7 +364,8 @@ func chanInit() *cobra.Command { return err } - return sendAndPrint([]sdk.Msg{chains[src].PathEnd.ChanInit(chains[dst].PathEnd, chains[src].MustGetAddress())}, chains[src], cmd) + return sendAndPrint([]sdk.Msg{chains[src].PathEnd.ChanInit(chains[dst].PathEnd, chains[src].MustGetAddress())}, + chains[src], cmd) }, } return cmd @@ -362,7 +373,8 @@ func chanInit() *cobra.Command { func chanTry() *cobra.Command { cmd := &cobra.Command{ - Use: "chan-try [src-chain-id] [dst-chain-id] [src-client-id] [src-conn-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]", + Use: strings.TrimSpace(`chan-try [src-chain-id] [dst-chain-id] + [src-client-id] [src-conn-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]`), Short: "chan-try", Args: cobra.ExactArgs(8), RunE: func(cmd *cobra.Command, args []string) error { @@ -403,7 +415,8 @@ func chanTry() *cobra.Command { func chanAck() *cobra.Command { cmd := &cobra.Command{ - Use: "chan-ack [src-chain-id] [dst-chain-id] [src-client-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]", + Use: strings.TrimSpace(`chan-ack [src-chain-id] [dst-chain-id] [src-client-id] + [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]`), Short: "chan-ack", Args: cobra.ExactArgs(7), RunE: func(cmd *cobra.Command, args []string) error { @@ -444,7 +457,8 @@ func chanAck() *cobra.Command { func chanConfirm() *cobra.Command { cmd := &cobra.Command{ - Use: "chan-confirm [src-chain-id] [dst-chain-id] [src-client-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]", + Use: strings.TrimSpace(`chan-confirm [src-chain-id] [dst-chain-id] [src-client-id] + [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]`), Short: "chan-confirm", Args: cobra.ExactArgs(7), RunE: func(cmd *cobra.Command, args []string) error { @@ -485,7 +499,8 @@ func chanConfirm() *cobra.Command { func createChannelStepCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "channel-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] [src-connection-id] [dst-connection-id] [src-channel-id] [dst-channel-id] [src-port-id] [dst-port-id] [ordering]", + Use: strings.TrimSpace(`channel-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] + [src-connection-id] [dst-connection-id] [src-channel-id] [dst-channel-id] [src-port-id] [dst-port-id] [ordering]`), Aliases: []string{"chan-step"}, Short: "create the next step in creating a channel between chains with the passed identifiers", Args: cobra.ExactArgs(11), @@ -549,7 +564,8 @@ func chanCloseInit() *cobra.Command { func chanCloseConfirm() *cobra.Command { cmd := &cobra.Command{ - Use: "chan-close-confirm [src-chain-id] [dst-chain-id] [src-client-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]", + Use: strings.TrimSpace(`chan-close-confirm [src-chain-id] [dst-chain-id] + [src-client-id] [src-chan-id] [dst-chan-id] [src-port-id] [dst-port-id]`), Short: "chan-close-confirm", Args: cobra.ExactArgs(7), RunE: func(cmd *cobra.Command, args []string) error { @@ -590,7 +606,8 @@ func chanCloseConfirm() *cobra.Command { func closeChannelStepCmd() *cobra.Command { cmd := &cobra.Command{ - Use: "close-channel-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] [src-connection-id] [dst-connection-id] [src-channel-id] [dst-channel-id] [src-port-id] [dst-port-id]", + Use: strings.TrimSpace(`close-channel-step [src-chain-id] [dst-chain-id] [src-client-id] [dst-client-id] + [src-connection-id] [dst-connection-id] [src-channel-id] [dst-channel-id] [src-port-id] [dst-port-id]`), Short: "create the next step in closing a channel between chains with the passed identifiers", Args: cobra.ExactArgs(10), RunE: func(cmd *cobra.Command, args []string) error { diff --git a/cmd/start.go b/cmd/start.go index 40c3e6934..19f33e747 100644 --- a/cmd/start.go +++ b/cmd/start.go @@ -65,7 +65,7 @@ func trapSignal(done func()) { // wait for a signal sig := <-sigCh - fmt.Println("Signal Recieved:", sig.String()) + fmt.Println("Signal Received", sig.String()) close(sigCh) // call the cleanup func diff --git a/cmd/strategy.go b/cmd/strategy.go index e3318d7ea..c0d92b1ab 100644 --- a/cmd/strategy.go +++ b/cmd/strategy.go @@ -14,7 +14,8 @@ func GetStrategyWithOptions(cmd *cobra.Command, strategy relayer.Strategy) (rela case (&relayer.NaiveStrategy{}).GetType(): ns, ok := strategy.(*relayer.NaiveStrategy) if !ok { - return strategy, fmt.Errorf("strategy.GetType() returns naive, but strategy type (%T) is not type NaiveStrategy", strategy) + return strategy, + fmt.Errorf("strategy.GetType() returns naive, but strategy type (%T) is not type NaiveStrategy", strategy) } diff --git a/cmd/testnets.go b/cmd/testnets.go index 3d749aaed..a8062e200 100644 --- a/cmd/testnets.go +++ b/cmd/testnets.go @@ -79,7 +79,7 @@ func faucetRequestCmd() *cobra.Command { if err != nil { return err } - + //nolint:gosec // Potential HTTP request made with variable url resp, err := http.Post(urlString, "application/json", bytes.NewBuffer(body)) if err != nil { return err diff --git a/cmd/tx.go b/cmd/tx.go index a4cd5b95b..c1266fccb 100644 --- a/cmd/tx.go +++ b/cmd/tx.go @@ -30,7 +30,8 @@ func transactionCmd() *cobra.Command { Use: "transact", Aliases: []string{"tx"}, Short: "IBC Transaction Commands", - Long: strings.TrimSpace(`Commands to create IBC transactions on configured chains. Most of these commands take a '[path]' arguement. Make sure: + Long: strings.TrimSpace(`Commands to create IBC transactions on configured chains. + Most of these commands take a '[path]' argument. Make sure: 1. Chains are properly configured to relay over by using the 'rly chains list' command 2. Path is properly configured to relay over by using the 'rly paths list' command`), } @@ -75,8 +76,9 @@ func createConnectionCmd() *cobra.Command { Use: "connection [path-name]", Aliases: []string{"conn"}, Short: "create a connection between two configured chains with a configured path", - Long: "This command is meant to be used to repair or create a connection between two chains with a configured path in the config file", - Args: cobra.ExactArgs(1), + Long: strings.TrimSpace(`This command is meant to be used to repair or create + a connection between two chains with a configured path in the config file`), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { c, src, dst, err := config.ChainsFromPath(args[0]) if err != nil { @@ -100,8 +102,9 @@ func createChannelCmd() *cobra.Command { Use: "channel [path-name]", Aliases: []string{"chan"}, Short: "create a channel between two configured chains with a configured path", - Long: "This command is meant to be used to repair or create a channel between two chains with a configured path in the config file", - Args: cobra.ExactArgs(1), + Long: strings.TrimSpace(`This command is meant to be used to repair or + create a channel between two chains with a configured path in the config file`), + Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { c, src, dst, err := config.ChainsFromPath(args[0]) if err != nil { diff --git a/cmd/xfer.go b/cmd/xfer.go index e4a62c8e6..9d7ec37de 100644 --- a/cmd/xfer.go +++ b/cmd/xfer.go @@ -43,14 +43,14 @@ func xfersend() *cobra.Command { if err != nil { return err } - - done := c[dst].UseSDKContext() + + done := c[dst].UseSDKContext() dstAddr, err := sdk.AccAddressFromBech32(args[4]) if err != nil { return err } - done () - + done() + return c[src].SendTransferMsg(c[dst], amount, dstAddr, source) }, } diff --git a/relayer/chain.go b/relayer/chain.go index c8b5bd679..4c02927fa 100644 --- a/relayer/chain.go +++ b/relayer/chain.go @@ -92,11 +92,12 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { for { select { case srcMsg := <-srcTxEvents: - if tx { + switch { + case tx: continue - } else if data { + case data: mar = srcMsg - } else { + default: mar = srcMsg.Events } if byt, err = json.Marshal(mar); err != nil { @@ -104,11 +105,12 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { } fmt.Println(string(byt)) case srcMsg := <-srcBlockEvents: - if block { + switch { + case block: continue - } else if data { + case data: mar = srcMsg - } else { + default: mar = srcMsg.Events } if byt, err = json.Marshal(mar); err != nil { @@ -124,7 +126,8 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { // Init initializes the pieces of a chain that aren't set when it parses a config // NOTE: All validation of the chain should happen here. -func (src *Chain) Init(homePath string, cdc *codecstd.Codec, amino *aminocodec.Codec, timeout time.Duration, debug bool) error { +func (src *Chain) Init(homePath string, cdc *codecstd.Codec, amino *aminocodec.Codec, + timeout time.Duration, debug bool) error { keybase, err := keys.New(src.ChainID, "test", keysDir(homePath, src.ChainID), nil) if err != nil { return err @@ -375,7 +378,7 @@ func (src *Chain) Update(key, value string) (out *Chain, err error) { return out, fmt.Errorf("key %s not found", key) } - return + return out, err } // Print fmt.Printlns the json or yaml representation of whatever is passed in diff --git a/relayer/faucet.go b/relayer/faucet.go index db1449f63..ee2d72603 100644 --- a/relayer/faucet.go +++ b/relayer/faucet.go @@ -56,7 +56,7 @@ func (src *Chain) FaucetHandler(fromKey sdk.AccAddress, amount sdk.Coin) func(w byt, err := ioutil.ReadAll(r.Body) if err != nil { str := "Failed to read request body" - src.Error(fmt.Errorf(str)) + src.Error(fmt.Errorf("%s: %w", str, err)) respondWithError(w, http.StatusBadGateway, str) return } @@ -118,7 +118,8 @@ func (src *Chain) checkAddress(addr string) (time.Duration, error) { sinceLastRequest := time.Since(val) if faucetTimeout > sinceLastRequest { wait := faucetTimeout - sinceLastRequest - return wait, fmt.Errorf("%s has requested funds within the last %s, wait %s before trying again", addr, faucetTimeout.String(), wait.String()) + return wait, fmt.Errorf("%s has requested funds within the last %s, wait %s before trying again", + addr, faucetTimeout.String(), wait.String()) } } src.faucetAddrs[addr] = time.Now() diff --git a/relayer/ics24.go b/relayer/ics24.go index 2625a476c..aceae4cf8 100644 --- a/relayer/ics24.go +++ b/relayer/ics24.go @@ -7,22 +7,22 @@ import ( host "github.com/cosmos/cosmos-sdk/x/ibc/24-host" ) -// Vclient validates the client identifer in the path +// Vclient validates the client identifier in the path func (p *PathEnd) Vclient() error { return host.ClientIdentifierValidator(p.ClientID) } -// Vconn validates the connection identifer in the path +// Vconn validates the connection identifier in the path func (p *PathEnd) Vconn() error { return host.ConnectionIdentifierValidator(p.ConnectionID) } -// Vchan validates the channel identifer in the path +// Vchan validates the channel identifier in the path func (p *PathEnd) Vchan() error { return host.ChannelIdentifierValidator(p.ChannelID) } -// Vport validates the port identifer in the path +// Vport validates the port identifier in the path func (p *PathEnd) Vport() error { return host.PortIdentifierValidator(p.PortID) } @@ -32,8 +32,8 @@ func (p PathEnd) String() string { } // PathSet check if the chain has a path set -func (c *Chain) PathSet() bool { - return c.PathEnd != nil +func (src *Chain) PathSet() bool { + return src.PathEnd != nil } // PathsSet checks if the chains have their paths set @@ -47,18 +47,19 @@ func PathsSet(chains ...*Chain) bool { } // SetPath sets the path and validates the identifiers -func (c *Chain) SetPath(p *PathEnd) error { +func (src *Chain) SetPath(p *PathEnd) error { err := p.Validate() if err != nil { - return c.ErrCantSetPath(err) + return src.ErrCantSetPath(err) } - c.PathEnd = p + src.PathEnd = p return nil } // AddPath takes the elements of a path and validates then, setting that path to the chain -func (c *Chain) AddPath(clientID, connectionID, channelID, port, order string) error { - return c.SetPath(&PathEnd{ChainID: c.ChainID, ClientID: clientID, ConnectionID: connectionID, ChannelID: channelID, PortID: port, Order: order}) +func (src *Chain) AddPath(clientID, connectionID, channelID, port, order string) error { + return src.SetPath(&PathEnd{ChainID: src.ChainID, ClientID: clientID, + ConnectionID: connectionID, ChannelID: channelID, PortID: port, Order: order}) } // Validate returns errors about invalid identifiers as well as @@ -83,11 +84,11 @@ func (p *PathEnd) Validate() error { } // ErrPathNotSet returns information what identifiers are needed to relay -func (c *Chain) ErrPathNotSet() error { - return fmt.Errorf("Path on chain %s not set", c.ChainID) +func (src *Chain) ErrPathNotSet() error { + return fmt.Errorf("path on chain %s not set", src.ChainID) } // ErrCantSetPath returns an error if the path doesn't set properly -func (c *Chain) ErrCantSetPath(err error) error { - return fmt.Errorf("Path on chain %s failed to set: %w", c.ChainID, err) +func (src *Chain) ErrCantSetPath(err error) error { + return fmt.Errorf("path on chain %s failed to set: %w", src.ChainID, err) } diff --git a/relayer/log-tx.go b/relayer/log-tx.go index 0ea1d8189..c499c8ddb 100644 --- a/relayer/log-tx.go +++ b/relayer/log-tx.go @@ -22,7 +22,8 @@ func (c *Chain) LogFailedTx(res sdk.TxResponse, err error, msgs []sdk.Msg) { } if res.Codespace != "" && res.Code != 0 { - c.logger.Info(fmt.Sprintf("✘ [%s]@{%d} - msg(%s) err(%s:%d:%s)", c.ChainID, res.Height, getMsgAction(msgs), res.Codespace, res.Code, res.RawLog)) + c.logger.Info(fmt.Sprintf("✘ [%s]@{%d} - msg(%s) err(%s:%d:%s)", + c.ChainID, res.Height, getMsgAction(msgs), res.Codespace, res.Code, res.RawLog)) } if c.debug && !res.Empty() { @@ -37,7 +38,8 @@ func (c *Chain) LogSuccessTx(res sdk.TxResponse, msgs []sdk.Msg) { } func (c *Chain) logPacketsRelayed(dst *Chain, num int) { - dst.Log(fmt.Sprintf("★ Relayed %d packets: [%s]port{%s}->[%s]port{%s}", num, dst.ChainID, dst.PathEnd.PortID, c.ChainID, c.PathEnd.PortID)) + dst.Log(fmt.Sprintf("★ Relayed %d packets: [%s]port{%s}->[%s]port{%s}", + num, dst.ChainID, dst.PathEnd.PortID, c.ChainID, c.PathEnd.PortID)) } func logChannelStates(src, dst *Chain, conn map[string]chanTypes.ChannelResponse) { @@ -68,7 +70,8 @@ func logConnectionStates(src, dst *Chain, conn map[string]connTypes.ConnectionRe } func (c *Chain) logCreateClient(dst *Chain, dstH uint64) { - c.Log(fmt.Sprintf("- [%s] -> creating client (%s) for [%s]header-height{%d} trust-period(%s)", c.ChainID, c.PathEnd.ClientID, dst.ChainID, dstH, dst.GetTrustingPeriod())) + c.Log(fmt.Sprintf("- [%s] -> creating client (%s) for [%s]header-height{%d} trust-period(%s)", + c.ChainID, c.PathEnd.ClientID, dst.ChainID, dstH, dst.GetTrustingPeriod())) } func (c *Chain) logTx(events map[string][]string) { diff --git a/relayer/naive-strategy.go b/relayer/naive-strategy.go index 4ff695116..c933e4d84 100644 --- a/relayer/naive-strategy.go +++ b/relayer/naive-strategy.go @@ -40,7 +40,7 @@ func (nrs *NaiveStrategy) UnrelayedSequencesUnordered(src, dst *Chain, sh *SyncH return UnrelayedSequences(src, dst, sh) } -// HandleEvents defines how the relayer will handle block and transaction events as they are emmited +// HandleEvents defines how the relayer will handle block and transaction events as they are emitted func (nrs *NaiveStrategy) HandleEvents(src, dst *Chain, sh *SyncHeaders, events map[string][]string) { rlyPackets, err := relayPacketsFromEventListener(src.PathEnd, dst.PathEnd, events) if len(rlyPackets) > 0 && err == nil { @@ -59,7 +59,8 @@ func relayPacketsFromEventListener(src, dst *PathEnd, events map[string][]string dstChan, dstPort := events["send_packet.packet_dst_channel"], events["send_packet.packet_dst_port"] // NOTE: Src and Dst are switched here - if dst.PortID == srcPort[i] && dst.ChannelID == srcChan[i] && src.PortID == dstPort[i] && src.ChannelID == dstChan[i] { + if dst.PortID == srcPort[i] && dst.ChannelID == srcChan[i] && + src.PortID == dstPort[i] && src.ChannelID == dstChan[i] { rp := &relayMsgRecvPacket{packetData: []byte(pd)} // next, get and parse the sequence @@ -104,7 +105,8 @@ func relayPacketsFromEventListener(src, dst *PathEnd, events map[string][]string dstChan, dstPort := events["recv_packet.packet_dst_channel"], events["recv_packet.packet_dst_port"] // NOTE: Src and Dst are not switched here - if src.PortID == srcPort[i] && src.ChannelID == srcChan[i] && dst.PortID == dstPort[i] && dst.ChannelID == dstChan[i] { + if src.PortID == srcPort[i] && src.ChannelID == srcChan[i] && + dst.PortID == dstPort[i] && dst.ChannelID == dstChan[i] { rp := &relayMsgPacketAck{packetData: []byte(pd)} // first get the ack @@ -143,7 +145,7 @@ func relayPacketsFromEventListener(src, dst *PathEnd, events map[string][]string } } } - return + return rlyPkts, nil } func (nrs *NaiveStrategy) sendTxFromEventPackets(src, dst *Chain, rlyPackets []relayPacket, sh *SyncHeaders) { @@ -227,7 +229,8 @@ func (nrs *NaiveStrategy) RelayPacketsOrderedChan(src, dst *Chain, sp *RelaySequ } if !msgs.Ready() { - src.Log(fmt.Sprintf("- No packets to relay between [%s]port{%s} and [%s]port{%s}", src.ChainID, src.PathEnd.PortID, dst.ChainID, dst.PathEnd.PortID)) + src.Log(fmt.Sprintf("- No packets to relay between [%s]port{%s} and [%s]port{%s}", + src.ChainID, src.PathEnd.PortID, dst.ChainID, dst.PathEnd.PortID)) return nil } @@ -286,7 +289,8 @@ func packetMsgFromTxQuery(src, dst *Chain, sh *SyncHeaders, seq uint64) (*Chain, // sanity check the sequence number against the one we are querying for // TODO: move this into relayPacketFromQueryResponse? if seq != rcvPackets[0].Seq() { - return nil, nil, fmt.Errorf("Different sequence number from query (%d vs %d)", seq, rcvPackets[0].Seq()) + return nil, nil, + fmt.Errorf("different sequence number from query (%d vs %d)", seq, rcvPackets[0].Seq()) } // fetch the proof from the sending chain @@ -302,7 +306,8 @@ func packetMsgFromTxQuery(src, dst *Chain, sh *SyncHeaders, seq uint64) (*Chain, // recv packets // relayPacketFromQueryResponse returned a timeout msg, create a timeout msg to be sent to original sender chain if seq != timeoutPackets[0].Seq() { - return nil, nil, fmt.Errorf("Different sequence number from query (%d vs %d)", seq, timeoutPackets[0].Seq()) + return nil, nil, + fmt.Errorf("different sequence number from query (%d vs %d)", seq, timeoutPackets[0].Seq()) } // fetch the timeout proof from the receiving chain @@ -317,7 +322,8 @@ func packetMsgFromTxQuery(src, dst *Chain, sh *SyncHeaders, seq uint64) (*Chain, // relayPacketFromQueryResponse looks through the events in a sdk.Response // and returns relayPackets with the appropriate data -func relayPacketFromQueryResponse(src, dst *PathEnd, res sdk.TxResponse, sh *SyncHeaders) (rcvPackets []relayPacket, timeoutPackets []relayPacket, err error) { +func relayPacketFromQueryResponse(src, dst *PathEnd, res sdk.TxResponse, + sh *SyncHeaders) (rcvPackets []relayPacket, timeoutPackets []relayPacket, err error) { for _, l := range res.Logs { for _, e := range l.Events { if e.Type == "send_packet" { diff --git a/relayer/packet-tx.go b/relayer/packet-tx.go index bf0dd43e8..7fe4c61f0 100644 --- a/relayer/packet-tx.go +++ b/relayer/packet-tx.go @@ -28,7 +28,8 @@ func defaultPacketTimeoutStamp() uint64 { } // SendTransferBothSides sends a ICS20 packet from src to dst -func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, dstAddr sdk.AccAddress, source bool) error { +func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, + dstAddr fmt.Stringer, source bool) error { if source { amount.Denom = fmt.Sprintf("%s/%s/%s", dst.PathEnd.PortID, dst.PathEnd.ChannelID, amount.Denom) } else { @@ -140,7 +141,7 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, dstAddr sdk } // SendTransferMsg initiates an ibs20 transfer from src to dst with the specified args -func (src *Chain) SendTransferMsg(dst *Chain, amount sdk.Coin, dstAddr sdk.AccAddress, source bool) error { +func (src *Chain) SendTransferMsg(dst *Chain, amount sdk.Coin, dstAddr fmt.Stringer, source bool) error { if source { amount.Denom = fmt.Sprintf("%s/%s/%s", dst.PathEnd.PortID, dst.PathEnd.ChannelID, amount.Denom) } else { diff --git a/relayer/path.go b/relayer/path.go index 2e6a21646..53e66b849 100644 --- a/relayer/path.go +++ b/relayer/path.go @@ -3,9 +3,10 @@ package relayer import ( "fmt" + "gopkg.in/yaml.v2" + tmclient "github.com/cosmos/cosmos-sdk/x/ibc/07-tendermint/types" ibctypes "github.com/cosmos/cosmos-sdk/x/ibc/types" - "gopkg.in/yaml.v2" ) var ( // Default identifiers for dummy usage @@ -117,7 +118,8 @@ func (p *Path) Validate() (err error) { return err } if p.Src.Order != p.Dst.Order { - return fmt.Errorf("Both sides must have same order ('ORDERED' or 'UNORDERED'), got src(%s) and dst(%s)", p.Src.Order, p.Dst.Order) + return fmt.Errorf("both sides must have same order ('ORDERED' or 'UNORDERED'), got src(%s) and dst(%s)", + p.Src.Order, p.Dst.Order) } return nil } diff --git a/relayer/pathEnd.go b/relayer/pathEnd.go index fdb4a4ef2..0eda03186 100644 --- a/relayer/pathEnd.go +++ b/relayer/pathEnd.go @@ -54,7 +54,8 @@ func (src *PathEnd) UpdateClient(dstHeader *tmclient.Header, signer sdk.AccAddre } // CreateClient creates an sdk.Msg to update the client on src with consensus state from dst -func (src *PathEnd) CreateClient(dstHeader *tmclient.Header, trustingPeriod time.Duration, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) CreateClient(dstHeader *tmclient.Header, trustingPeriod time.Duration, + signer sdk.AccAddress) sdk.Msg { if err := dstHeader.ValidateBasic(dstHeader.ChainID); err != nil { panic(err) } @@ -83,7 +84,8 @@ func (src *PathEnd) ConnInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { // ConnTry creates a MsgConnectionOpenTry // NOTE: ADD NOTE ABOUT PROOF HEIGHT CHANGE HERE -func (src *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionResponse, + dstConsState clientTypes.ConsensusStateResponse, dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenTry( src.ConnectionID, src.ClientID, @@ -101,7 +103,8 @@ func (src *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionRespo // ConnAck creates a MsgConnectionOpenAck // NOTE: ADD NOTE ABOUT PROOF HEIGHT CHANGE HERE -func (src *PathEnd) ConnAck(dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) ConnAck(dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, + dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenAck( src.ConnectionID, dstConnState.Proof, @@ -199,7 +202,8 @@ func (src *PathEnd) ChanCloseConfirm(dstChanState chanTypes.ChannelResponse, sig } // MsgRecvPacket creates a MsgPacket -func (src *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, packetData []byte, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, + packetData []byte, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgPacket( dst.NewPacket( src, @@ -215,7 +219,8 @@ func (src *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeout } // MsgTimeout creates MsgTimeout -func (src *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, timeoutStamp uint64, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, timeoutStamp uint64, + proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgTimeout( src.NewPacket( dst, @@ -232,7 +237,8 @@ func (src *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, ti } // MsgAck creates MsgAck -func (src *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, ack, packetData []byte, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, ack, packetData []byte, + proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgAcknowledgement( src.NewPacket( dst, @@ -249,7 +255,8 @@ func (src *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp u } // MsgTransfer creates a new transfer message -func (src *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins, dstAddr string, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins, dstAddr string, + signer sdk.AccAddress) sdk.Msg { return xferTypes.NewMsgTransfer( src.PortID, src.ChannelID, @@ -261,15 +268,18 @@ func (src *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins } // MsgSendPacket creates a new arbitrary packet message -func (src *PathEnd) MsgSendPacket(dst *PathEnd, packetData []byte, relativeTimeout, timeoutStamp uint64, signer sdk.AccAddress) sdk.Msg { +func (src *PathEnd) MsgSendPacket(dst *PathEnd, packetData []byte, relativeTimeout, timeoutStamp uint64, + signer sdk.AccAddress) sdk.Msg { // NOTE: Use this just to pass the packet integrity checks. fakeSequence := uint64(1) - packet := chanTypes.NewPacket(packetData, fakeSequence, src.PortID, src.ChannelID, dst.PortID, dst.ChannelID, relativeTimeout, timeoutStamp) + packet := chanTypes.NewPacket(packetData, fakeSequence, src.PortID, src.ChannelID, dst.PortID, + dst.ChannelID, relativeTimeout, timeoutStamp) return NewMsgSendPacket(packet, signer) } // NewPacket returns a new packet from src to dist w -func (src *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, timeoutHeight, timeoutStamp uint64) chanTypes.Packet { +func (src *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, + timeoutHeight, timeoutStamp uint64) chanTypes.Packet { return chanTypes.NewPacket( packetData, sequence, @@ -283,16 +293,17 @@ func (src *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, } // XferPacket creates a new transfer packet -func (src *PathEnd) XferPacket(amount sdk.Coins, sender, reciever string) []byte { +func (src *PathEnd) XferPacket(amount sdk.Coins, sender, receiver string) []byte { return xferTypes.NewFungibleTokenPacketData( amount, sender, - reciever, + receiver, ).GetBytes() } // PacketMsg returns a new MsgPacket for forwarding packets from one chain to another -func (src *Chain) PacketMsg(dst *Chain, xferPacket []byte, timeout, timeoutStamp uint64, seq int64, dstCommitRes CommitmentResponse) sdk.Msg { +func (src *Chain) PacketMsg(dst *Chain, xferPacket []byte, timeout, timeoutStamp uint64, + seq int64, dstCommitRes CommitmentResponse) sdk.Msg { return src.PathEnd.MsgRecvPacket( dst.PathEnd, uint64(seq), diff --git a/relayer/query.go b/relayer/query.go index 031662cbe..1e4389459 100644 --- a/relayer/query.go +++ b/relayer/query.go @@ -14,7 +14,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" clientExported "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" clientTypes "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" connTypes "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" @@ -118,7 +117,8 @@ func qConsStateErr(err error) error { return fmt.Errorf("query cons state failed // QueryClientConsensusState retrevies the latest consensus state for a client in state at a given height // NOTE: dstHeight is the height from dst that is stored on src, it is needed to construct the appropriate store query -func (c *Chain) QueryClientConsensusState(srcHeight, srcClientConsHeight int64) (clientTypes.ConsensusStateResponse, error) { +func (c *Chain) QueryClientConsensusState(srcHeight, + srcClientConsHeight int64) (clientTypes.ConsensusStateResponse, error) { var conStateRes clientTypes.ConsensusStateResponse if !c.PathSet() { return conStateRes, c.ErrPathNotSet() @@ -126,7 +126,7 @@ func (c *Chain) QueryClientConsensusState(srcHeight, srcClientConsHeight int64) req := abci.RequestQuery{ Path: "store/ibc/key", - Height: int64(srcHeight), + Height: srcHeight, Data: prefixClientKey(c.PathEnd.ClientID, ibctypes.KeyConsensusState(uint64(srcClientConsHeight))), Prove: true, } @@ -139,7 +139,7 @@ func (c *Chain) QueryClientConsensusState(srcHeight, srcClientConsHeight int64) return clientTypes.NewConsensusStateResponse("notfound", nil, nil, 0), nil } - var cs exported.ConsensusState + var cs clientExported.ConsensusState if err = c.Amino.UnmarshalBinaryLengthPrefixed(res.Value, &cs); err != nil { if err = c.Amino.UnmarshalBinaryBare(res.Value, &cs); err != nil { return conStateRes, qClntConsStateErr(err) @@ -162,7 +162,8 @@ type chh struct { } // QueryClientConsensusStatePair allows for the querying of multiple client states at the same time -func QueryClientConsensusStatePair(src, dst *Chain, srcH, dstH, srcClientConsH, dstClientConsH int64) (map[string]clientTypes.ConsensusStateResponse, error) { +func QueryClientConsensusStatePair(src, dst *Chain, + srcH, dstH, srcClientConsH, dstClientConsH int64) (map[string]clientTypes.ConsensusStateResponse, error) { hs := &csstates{ Map: make(map[string]clientTypes.ConsensusStateResponse), Errs: []error{}, @@ -217,7 +218,7 @@ func (c *Chain) QueryClientState() (*clientTypes.StateResponse, error) { return nil, nil } - var cs exported.ClientState + var cs clientExported.ClientState // If this decoding fails, try with UnmarshalBinaryLengthPrefixed this changed // reciently and will help support older versions. @@ -281,7 +282,8 @@ func (c *Chain) QueryClients(page, limit int) ([]clientExported.ClientState, err return nil, qClntsErr(err) } - if bz, _, err = c.QueryWithData(ibcQuerierRoute(clientTypes.QuerierRoute, clientTypes.QueryAllClients), bz); err != nil { + if bz, _, err = c.QueryWithData( + ibcQuerierRoute(clientTypes.QuerierRoute, clientTypes.QueryAllClients), bz); err != nil { return nil, qClntsErr(err) } @@ -305,7 +307,8 @@ func (c *Chain) QueryConnections(page, limit int) (conns []connTypes.ConnectionE return nil, qConnsErr(err) } - if bz, _, err = c.QueryWithData(ibcQuerierRoute(connTypes.QuerierRoute, connTypes.QueryAllConnections), bz); err != nil { + if bz, _, err = c.QueryWithData( + ibcQuerierRoute(connTypes.QuerierRoute, connTypes.QueryAllConnections), bz); err != nil { return nil, qConnsErr(err) } @@ -430,7 +433,6 @@ func QueryConnectionPair(src, dst *Chain, srcH, dstH int64) (map[string]connType func qConnErr(err error) error { return fmt.Errorf("query connection failed: %w", err) } -var emptyConn = connTypes.ConnectionEnd{State: ibctypes.UNINITIALIZED} var emptyConnRes = connTypes.ConnectionResponse{Connection: connTypes.ConnectionEnd{ID: ""}} // //////////////////////////// @@ -449,7 +451,8 @@ func (c *Chain) QueryConnectionChannels(connectionID string, page, limit int) ([ return nil, qChansErr(err) } - if bz, _, err = c.QueryWithData(ibcQuerierRoute(chanTypes.QuerierRoute, chanTypes.QueryConnectionChannels), bz); err != nil { + if bz, _, err = c.QueryWithData( + ibcQuerierRoute(chanTypes.QuerierRoute, chanTypes.QueryConnectionChannels), bz); err != nil { return nil, qChansErr(err) } @@ -478,7 +481,8 @@ func (c *Chain) QueryChannel(height int64) (chanRes chanTypes.ChannelResponse, e return chanRes, qChanErr(err) } else if res.Value == nil { // NOTE: This is returned so that the switch statement in ChannelStep works properly - return chanTypes.NewChannelResponse(c.PathEnd.PortID, c.PathEnd.ChannelID, chanTypes.Channel{State: ibctypes.UNINITIALIZED}, nil, 0), nil + return chanTypes.NewChannelResponse(c.PathEnd.PortID, c.PathEnd.ChannelID, + chanTypes.Channel{State: ibctypes.UNINITIALIZED}, nil, 0), nil } var channel chanTypes.Channel @@ -944,7 +948,7 @@ func QueryPathStatus(src, dst *Chain, path *Path) (stat *PathStatus, err error) return } stat.UnrelayedSeq = unrelayed - return + return stat, err } // QueryTx takes a transaction hash and returns the transaction @@ -1184,7 +1188,8 @@ func (c *Chain) queryBlocksForTxResults(resTxs []*ctypes.ResultTx) (map[int64]*c } // formatTxResults parses the indexed txs into a slice of TxResponse objects. -func (c *Chain) formatTxResults(resTxs []*ctypes.ResultTx, resBlocks map[int64]*ctypes.ResultBlock) ([]sdk.TxResponse, error) { +func (c *Chain) formatTxResults(resTxs []*ctypes.ResultTx, + resBlocks map[int64]*ctypes.ResultBlock) ([]sdk.TxResponse, error) { var err error out := make([]sdk.TxResponse, len(resTxs)) for i := range resTxs { @@ -1231,7 +1236,7 @@ func ParseEvents(e string) ([]string, error) { events = append(events, eventsStr) } - var tmEvents []string + var tmEvents = make([]string, len(events)) for _, event := range events { if !strings.Contains(event, "=") { diff --git a/relayer/relayMsgs.go b/relayer/relayMsgs.go index 9e5daa4d3..a21e5e18a 100644 --- a/relayer/relayMsgs.go +++ b/relayer/relayMsgs.go @@ -45,8 +45,10 @@ func (r *RelayMsgs) IsMaxTx(msgLen, txSize uint64) bool { // Send sends the messages with appropriate output // TODO: Parallelize? Maybe? func (r *RelayMsgs) Send(src, dst *Chain) { - var msgLen, txSize uint64 - var msgs []sdk.Msg + var ( + msgLen, txSize uint64 + msgs = make([]sdk.Msg, len(r.Src)) + ) r.success = true @@ -103,10 +105,10 @@ func send(chain *Chain, msgs []sdk.Msg) bool { if err != nil || res.Code != 0 { chain.LogFailedTx(res, err, msgs) return false - } else { - // NOTE: Add more data to this such as identifiers - chain.LogSuccessTx(res, msgs) } + // NOTE: Add more data to this such as identifiers + chain.LogSuccessTx(res, msgs) + return true } diff --git a/relayer/relayPackets.go b/relayer/relayPackets.go index d1838ecea..a35541a66 100644 --- a/relayer/relayPackets.go +++ b/relayer/relayPackets.go @@ -48,7 +48,8 @@ func (rp *relayMsgTimeout) FetchCommitResponse(src, dst *Chain, sh *SyncHeaders) if err != nil { return err } else if dstRecvRes.Proof.Proof == nil { - return fmt.Errorf("- [%s]@{%d} - Packet Commitment Proof is nil seq(%d)", dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) + return fmt.Errorf("- [%s]@{%d} - Packet Commitment Proof is nil seq(%d)", + dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) } return nil }); err != nil { @@ -118,7 +119,8 @@ func (rp *relayMsgRecvPacket) FetchCommitResponse(src, dst *Chain, sh *SyncHeade if err != nil { return err } else if dstCommitRes.Proof.Proof == nil { - return fmt.Errorf("- [%s]@{%d} - Packet Commitment Proof is nil seq(%d)", dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) + return fmt.Errorf("- [%s]@{%d} - Packet Commitment Proof is nil seq(%d)", + dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) } return nil }); err != nil { @@ -146,8 +148,6 @@ type relayMsgPacketAck struct { timeout uint64 timeoutStamp uint64 dstComRes *CommitmentResponse - - pass bool } func (rp *relayMsgPacketAck) Data() []byte { @@ -181,7 +181,8 @@ func (rp *relayMsgPacketAck) FetchCommitResponse(src, dst *Chain, sh *SyncHeader if err != nil { return err } else if dstCommitRes.Proof.Proof == nil { - return fmt.Errorf("- [%s]@{%d} - Packet Ack Proof is nil seq(%d)", dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) + return fmt.Errorf("- [%s]@{%d} - Packet Ack Proof is nil seq(%d)", + dst.ChainID, int64(sh.GetHeight(dst.ChainID)-1), rp.seq) } return nil }); err != nil { diff --git a/relayer/strategies.go b/relayer/strategies.go index e8c66a3dd..c0379adfc 100644 --- a/relayer/strategies.go +++ b/relayer/strategies.go @@ -23,21 +23,22 @@ type Strategy interface { } // MustGetStrategy returns the strategy and panics on error -func (r *Path) MustGetStrategy() Strategy { - strat, err := r.GetStrategy() +func (p *Path) MustGetStrategy() Strategy { + strategy, err := p.GetStrategy() if err != nil { panic(err) } - return strat + + return strategy } // GetStrategy the strategy defined in the relay messages -func (r *Path) GetStrategy() (Strategy, error) { - switch r.Strategy.Type { +func (p *Path) GetStrategy() (Strategy, error) { + switch p.Strategy.Type { case (&NaiveStrategy{}).GetType(): return &NaiveStrategy{}, nil default: - return nil, fmt.Errorf("invalid strategy: %s", r.Strategy.Type) + return nil, fmt.Errorf("invalid strategy: %s", p.Strategy.Type) } } diff --git a/relayer/verifier.go b/relayer/verifier.go index 700c409c1..94b4cff71 100644 --- a/relayer/verifier.go +++ b/relayer/verifier.go @@ -120,7 +120,7 @@ func (c *Chain) UpdateLiteWithHeaderHeight(height int64) (*tmclient.Header, erro } // LiteClientWithoutTrust reads the trusted period off of the chain. -func (c *Chain) LiteClientWithoutTrust(db *dbm.GoLevelDB) (*lite.Client, error) { +func (c *Chain) LiteClientWithoutTrust(db dbm.DB) (*lite.Client, error) { httpProvider, err := litehttp.New(c.ChainID, c.RPCAddr) if err != nil { return nil, err @@ -139,7 +139,7 @@ func (c *Chain) LiteClientWithoutTrust(db *dbm.GoLevelDB) (*lite.Client, error) } // LiteClient initializes the lite client for a given chain. -func (c *Chain) LiteClient(db *dbm.GoLevelDB, trustOpts lite.TrustOptions) (*lite.Client, error) { +func (c *Chain) LiteClient(db dbm.DB, trustOpts lite.TrustOptions) (*lite.Client, error) { httpProvider, err := litehttp.New(c.ChainID, c.RPCAddr) if err != nil { return nil, err @@ -158,7 +158,7 @@ func (c *Chain) LiteClient(db *dbm.GoLevelDB, trustOpts lite.TrustOptions) (*lit } // InitLiteClient instantantiates the lite client object and calls update -func (c *Chain) InitLiteClient(db *dbm.GoLevelDB, trustOpts lite.TrustOptions) (*lite.Client, error) { +func (c *Chain) InitLiteClient(db dbm.DB, trustOpts lite.TrustOptions) (*lite.Client, error) { lc, err := c.LiteClient(db, trustOpts) if err != nil { return nil, err @@ -171,7 +171,7 @@ func (c *Chain) InitLiteClient(db *dbm.GoLevelDB, trustOpts lite.TrustOptions) ( } // TrustNodeInitClient trusts the configured node and initializes the lite client -func (c *Chain) TrustNodeInitClient(db *dbm.GoLevelDB) (*lite.Client, error) { +func (c *Chain) TrustNodeInitClient(db dbm.DB) (*lite.Client, error) { // fetch latest height from configured node var ( height int64 @@ -310,7 +310,7 @@ func (c *Chain) GetLiteSignedHeaderAtHeight(height int64) (*tmclient.Header, err return &tmclient.Header{SignedHeader: *sh, ValidatorSet: vs}, nil } -// ErrLiteNotInitialized returns the cannonical error for a an uninitialized lite client +// ErrLiteNotInitialized returns the canonical error for a an uninitialized lite client var ErrLiteNotInitialized = errors.New("lite client is not initialized") // ForceInitLite forces initialization of the lite client from the configured node diff --git a/test/relayer_coco_test.go b/test/relayer_coco_test.go index fb1d5d55e..71d764d29 100644 --- a/test/relayer_coco_test.go +++ b/test/relayer_coco_test.go @@ -2,8 +2,9 @@ package test import ( "testing" - + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/iqlusioninc/relayer/relayer" "github.com/stretchr/testify/require" ) @@ -17,7 +18,7 @@ var ( func TestCoCo_CoCoToFFtStreamingRelayer(t *testing.T) { chains := spinUpTestChains(t, cocoChains...) - + var ( src = chains.MustGet("coco-post-chain") dst = chains.MustGet("ibc") @@ -28,16 +29,16 @@ func TestCoCo_CoCoToFFtStreamingRelayer(t *testing.T) { testCoinDst = sdk.NewCoin(testDenomDst, sdk.NewInt(1000)) twoTestCoinDst = sdk.NewCoin(testDenomDst, sdk.NewInt(2000)) ) - + path, err := genTestPathAndSet(src, dst, "transfer", "transfer") require.NoError(t, err) - + // query initial balances to compare against at the end srcExpected, err := src.QueryBalance(src.Key) require.NoError(t, err) dstExpected, err := dst.QueryBalance(dst.Key) require.NoError(t, err) - + // create path require.NoError(t, src.CreateClients(dst)) testClientPair(t, src, dst) @@ -45,51 +46,51 @@ func TestCoCo_CoCoToFFtStreamingRelayer(t *testing.T) { testConnectionPair(t, src, dst) require.NoError(t, src.CreateChannel(dst, true, src.GetTimeout())) testChannelPair(t, src, dst) - + // send a couple of transfers to the queue on src require.NoError(t, src.SendTransferMsg(dst, testCoinSrc, dst.MustGetAddress(), true)) require.NoError(t, src.SendTransferMsg(dst, testCoinSrc, dst.MustGetAddress(), true)) - + // send a couple of transfers to the queue on dst require.NoError(t, dst.SendTransferMsg(src, testCoinDst, src.MustGetAddress(), true)) require.NoError(t, dst.SendTransferMsg(src, testCoinDst, src.MustGetAddress(), true)) - + // Wait for message inclusion in both chains require.NoError(t, dst.WaitForNBlocks(1)) - + // start the relayer process in it's own goroutine rlyDone, err := relayer.RunStrategy(src, dst, path.MustGetStrategy(), path.Ordered()) require.NoError(t, err) - + // send those tokens from dst back to dst and src back to src require.NoError(t, src.SendTransferMsg(dst, twoTestCoinDst, dst.MustGetAddress(), false)) require.NoError(t, dst.SendTransferMsg(src, twoTestCoinSrc, src.MustGetAddress(), false)) - + // wait for packet processing require.NoError(t, dst.WaitForNBlocks(4)) - + // kill relayer routine rlyDone() - + // check balance on src against expected srcGot, err := src.QueryBalance(src.Key) require.NoError(t, err) require.Equal(t, srcExpected.AmountOf(testDenomSrc).Int64(), srcGot.AmountOf(testDenomSrc).Int64()) - + // check balance on dst against expected dstGot, err := dst.QueryBalance(dst.Key) require.NoError(t, err) require.Equal(t, dstExpected.AmountOf(testDenomDst).Int64(), dstGot.AmountOf(testDenomDst).Int64()) - + // Test the full transfer command as well require.NoError(t, src.SendTransferBothSides(dst, testCoinSrc, dst.MustGetAddress(), true)) require.NoError(t, dst.SendTransferBothSides(src, testCoinSrc, src.MustGetAddress(), false)) - + // check balance on src against expected srcGot, err = src.QueryBalance(src.Key) require.NoError(t, err) require.Equal(t, srcExpected.AmountOf(testDenomSrc).Int64(), srcGot.AmountOf(testDenomSrc).Int64()) - + // check balance on dst against expected dstGot, err = dst.QueryBalance(dst.Key) require.NoError(t, err) diff --git a/test/test_chains.go b/test/test_chains.go index a79818933..e2a7521ac 100644 --- a/test/test_chains.go +++ b/test/test_chains.go @@ -11,7 +11,7 @@ import ( gaia "github.com/cosmos/gaia/app" "github.com/stretchr/testify/require" - . "github.com/iqlusioninc/relayer/relayer" + ry "github.com/iqlusioninc/relayer/relayer" ) var ( @@ -133,10 +133,11 @@ type ( ) // newTestChain generates a new instance of *Chain with a free TCP port configured as the RPC port -func newTestChain(t *testing.T, tc testChain) *Chain { +func newTestChain(t *testing.T, tc testChain) *ry.Chain { _, port, err := server.FreeTCPAddr() require.NoError(t, err) - return &Chain{ + + return &ry.Chain{ Key: "testkey", ChainID: tc.chainID, RPCAddr: fmt.Sprintf("http://localhost:%s", port), diff --git a/test/test_queries.go b/test/test_queries.go index 99137ee63..61c42e724 100644 --- a/test/test_queries.go +++ b/test/test_queries.go @@ -5,17 +5,17 @@ import ( "github.com/stretchr/testify/require" - . "github.com/iqlusioninc/relayer/relayer" + ry "github.com/iqlusioninc/relayer/relayer" ) // testClientPair tests that the client for src on dst and dst on src are the only clients on those chains -func testClientPair(t *testing.T, src, dst *Chain) { +func testClientPair(t *testing.T, src, dst *ry.Chain) { testClient(t, src, dst) testClient(t, dst, src) } -// testClient queries client for existance of dst on src -func testClient(t *testing.T, src, dst *Chain) { +// testClient queries client for existence of dst on src +func testClient(t *testing.T, src, dst *ry.Chain) { client, err := src.QueryClientState() require.NoError(t, err) require.NotNil(t, client) @@ -24,13 +24,13 @@ func testClient(t *testing.T, src, dst *Chain) { } // testConnectionPair tests that the only connection on src and dst is between the two chains -func testConnectionPair(t *testing.T, src, dst *Chain) { +func testConnectionPair(t *testing.T, src, dst *ry.Chain) { testConnection(t, src, dst) testConnection(t, dst, src) } // testConnection tests that the only connection on src has a counterparty that is the connection on dst -func testConnection(t *testing.T, src, dst *Chain) { +func testConnection(t *testing.T, src, dst *ry.Chain) { conns, err := src.QueryConnections(1, 1000) require.NoError(t, err) require.Equal(t, len(conns), 1) @@ -51,13 +51,13 @@ func testConnection(t *testing.T, src, dst *Chain) { } // testChannelPair tests that the only channel on src and dst is between the two chains -func testChannelPair(t *testing.T, src, dst *Chain) { +func testChannelPair(t *testing.T, src, dst *ry.Chain) { testChannel(t, src, dst) testChannel(t, dst, src) } // testChannel tests that the only channel on src is a counterparty of dst -func testChannel(t *testing.T, src, dst *Chain) { +func testChannel(t *testing.T, src, dst *ry.Chain) { chans, err := src.QueryChannels(1, 1000) require.NoError(t, err) require.Equal(t, 1, len(chans)) diff --git a/test/test_setup.go b/test/test_setup.go index 9fdf8ba46..dcd032ecb 100644 --- a/test/test_setup.go +++ b/test/test_setup.go @@ -13,16 +13,16 @@ import ( dc "github.com/ory/dockertest/v3/docker" "github.com/stretchr/testify/require" - . "github.com/iqlusioninc/relayer/relayer" + ry "github.com/iqlusioninc/relayer/relayer" ) // spinUpTestChains is to be passed any number of test chains with given configuration options // to be created as individual docker containers at the beginning of a test. It is safe to run // in parallel tests as all created resources are independent of eachother -func spinUpTestChains(t *testing.T, testChains ...testChain) Chains { +func spinUpTestChains(t *testing.T, testChains ...testChain) ry.Chains { var ( resources []*dockertest.Resource - chains []*Chain + chains = make([]*ry.Chain, len(testChains)) wg sync.WaitGroup rchan = make(chan *dockertest.Resource, len(testChains)) @@ -38,10 +38,10 @@ func spinUpTestChains(t *testing.T, testChains ...testChain) Chains { // uses a sensible default on windows (tcp/http) and linux/osx (socket) pool, err := dockertest.NewPool("") if err != nil { - require.NoError(t, fmt.Errorf("Could not connect to docker at %s: %w", pool.Client.Endpoint(), err)) + require.NoError(t, fmt.Errorf("could not connect to docker at %s: %w", pool.Client.Endpoint(), err)) } - // make each container and initalize the chains + // make each container and initialize the chains for _, tc := range testChains { c := newTestChain(t, tc) chains = append(chains, c) @@ -83,7 +83,7 @@ func removeTestContainer(pool *dockertest.Pool, containerName string) error { }, }) if err != nil { - return fmt.Errorf("Error while listing containers with name %s %w", containerName, err) + return fmt.Errorf("error while listing containers with name %s %w", containerName, err) } if len(containers) == 0 { @@ -96,14 +96,15 @@ func removeTestContainer(pool *dockertest.Pool, containerName string) error { RemoveVolumes: true, }) if err != nil { - return fmt.Errorf("Error while removing container with name %s %w", containerName, err) + return fmt.Errorf("error while removing container with name %s %w", containerName, err) } return nil } // spinUpTestContainer spins up a test container with the given configuration -func spinUpTestContainer(t *testing.T, rchan chan<- *dockertest.Resource, pool *dockertest.Pool, c *Chain, dir string, wg *sync.WaitGroup, tc testChain) { +func spinUpTestContainer(t *testing.T, rchan chan<- *dockertest.Resource, + pool *dockertest.Pool, c *ry.Chain, dir string, wg *sync.WaitGroup, tc testChain) { defer wg.Done() var err error @@ -151,23 +152,26 @@ func spinUpTestContainer(t *testing.T, rchan chan<- *dockertest.Resource, pool * resource, err = pool.RunWithOptions(dockerOpts) require.NoError(t, err) - c.Log(fmt.Sprintf("- [%s] SPUN UP IN CONTAINER %s from %s", c.ChainID, resource.Container.Name, resource.Container.Config.Image)) + c.Log(fmt.Sprintf("- [%s] SPUN UP IN CONTAINER %s from %s", c.ChainID, + resource.Container.Name, resource.Container.Config.Image)) // retry polling the container until status doesn't error if err = pool.Retry(c.StatusErr); err != nil { - require.NoError(t, fmt.Errorf("Could not connect to container at %s: %s", c.RPCAddr, err)) + require.NoError(t, fmt.Errorf("could not connect to container at %s: %s", c.RPCAddr, err)) } c.Log(fmt.Sprintf("- [%s] CONTAINER AVAILABLE AT PORT %s", c.ChainID, c.RPCAddr)) - // initalize the lite client + // initialize the lite client require.NoError(t, c.ForceInitLite()) rchan <- resource } -// cleanUpTest is called as a goroutine to wait until the tests have completed and cleans up the docker containers and relayer config -func cleanUpTest(t *testing.T, testsDone <-chan struct{}, contDone chan<- struct{}, resources []*dockertest.Resource, pool *dockertest.Pool, dir string, chains []*Chain) { +// cleanUpTest is called as a goroutine to wait until the tests have completed and +// cleans up the docker containers and relayer config +func cleanUpTest(t *testing.T, testsDone <-chan struct{}, contDone chan<- struct{}, + resources []*dockertest.Resource, pool *dockertest.Pool, dir string, chains []*ry.Chain) { // block here until tests are complete <-testsDone @@ -179,10 +183,11 @@ func cleanUpTest(t *testing.T, testsDone <-chan struct{}, contDone chan<- struct // remove all the docker containers for i, r := range resources { if err := pool.Purge(r); err != nil { - require.NoError(t, fmt.Errorf("Could not purge container %s: %w", r.Container.Name, err)) + require.NoError(t, fmt.Errorf("cculd not purge container %s: %w", r.Container.Name, err)) } c := getLoggingChain(chains, r) - chains[i].Log(fmt.Sprintf("- [%s] SPUN DOWN CONTAINER %s from %s", c.ChainID, r.Container.Name, r.Container.Config.Image)) + chains[i].Log(fmt.Sprintf("- [%s] SPUN DOWN CONTAINER %s from %s", c.ChainID, r.Container.Name, + r.Container.Config.Image)) } // Notify the other side that we have deleted the docker containers @@ -190,7 +195,7 @@ func cleanUpTest(t *testing.T, testsDone <-chan struct{}, contDone chan<- struct } // for the love of logs https://www.youtube.com/watch?v=DtsKcHmceqY -func getLoggingChain(chns []*Chain, rsr *dockertest.Resource) *Chain { +func getLoggingChain(chns []*ry.Chain, rsr *dockertest.Resource) *ry.Chain { for _, c := range chns { if strings.Contains(rsr.Container.Name, c.ChainID) { return c @@ -199,8 +204,8 @@ func getLoggingChain(chns []*Chain, rsr *dockertest.Resource) *Chain { return nil } -func genTestPathAndSet(src, dst *Chain, srcPort, dstPort string) (*Path, error) { - path := GenPath(src.ChainID, dst.ChainID, srcPort, dstPort, "ORDERED") +func genTestPathAndSet(src, dst *ry.Chain, srcPort, dstPort string) (*ry.Path, error) { + path := ry.GenPath(src.ChainID, dst.ChainID, srcPort, dstPort, "ORDERED") if err := src.SetPath(path.Src); err != nil { return nil, err } From 2174d8deb9cef391bdd6644f28c965275edf82f9 Mon Sep 17 00:00:00 2001 From: Marko Baricevic Date: Mon, 25 May 2020 15:30:04 +0200 Subject: [PATCH 02/17] minor cleanup in ci testing --- .github/workflows/gaia-tests.yml | 40 ++++++++++++-------------- .github/workflows/mtd-tests.yml | 35 +++++++++------------- .github/workflows/release.yml | 9 +++--- .github/workflows/rocketzone-tests.yml | 4 +-- 4 files changed, 38 insertions(+), 50 deletions(-) diff --git a/.github/workflows/gaia-tests.yml b/.github/workflows/gaia-tests.yml index a8dcebe6e..4dbb832e1 100644 --- a/.github/workflows/gaia-tests.yml +++ b/.github/workflows/gaia-tests.yml @@ -3,31 +3,29 @@ name: TESTING - gaia to gaia integration on: [push] jobs: - build: name: build runs-on: ubuntu-latest steps: + # Install and setup go + - name: Set up Go 1.14 + uses: actions/setup-go@v1 + with: + go-version: 1.14 + id: go - # Install and setup go - - name: Set up Go 1.14 - uses: actions/setup-go@v1 - with: - go-version: 1.14 - id: go + # checkout relayer + - name: checkout relayer + uses: actions/checkout@v2 - # checkout relayer - - name: checkout relayer - uses: actions/checkout@v2 + # build cache + - uses: actions/cache@v1 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- - # build cache - - uses: actions/cache@v1 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - # run tests - - name: run gaia tests - run: TEST_DEBUG=true make test-gaia + # run tests + - name: run gaia tests + run: make test-gaia diff --git a/.github/workflows/mtd-tests.yml b/.github/workflows/mtd-tests.yml index f8de5ab6e..0908a6de6 100644 --- a/.github/workflows/mtd-tests.yml +++ b/.github/workflows/mtd-tests.yml @@ -3,31 +3,22 @@ name: TESTING - mtd to ibc integration on: [push] jobs: - build: name: build runs-on: ubuntu-latest steps: + # checkout relayer + - name: checkout relayer + uses: actions/checkout@v2 - # Install and setup go - - name: Set up Go 1.14 - uses: actions/setup-go@v1 - with: - go-version: 1.14 - id: go - - # checkout relayer - - name: checkout relayer - uses: actions/checkout@v2 + # build cache + - uses: actions/cache@v1 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- - # build cache - - uses: actions/cache@v1 - with: - path: ~/go/pkg/mod - key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} - restore-keys: | - ${{ runner.os }}-go- - - # run tests - - name: run mtd tests - run: TEST_DEBUG=true make test-mtd + # run tests + - name: run mtd tests + run: make test-mtd diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 687093035..3b850e1d7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,8 +3,7 @@ on: push: # Sequence of patterns matched against refs/tags tags: - - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 - + - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10 jobs: build: @@ -27,12 +26,12 @@ jobs: draft: false prerelease: false - name: Upload Release Asset - id: upload-release-asset + id: upload-release-asset uses: actions/upload-release-asset@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps asset_path: ./release.tar.gz asset_name: release.tar.gz - asset_content_type: application/zip \ No newline at end of file + asset_content_type: application/zip diff --git a/.github/workflows/rocketzone-tests.yml b/.github/workflows/rocketzone-tests.yml index a5c61b13f..dc97fd7fb 100644 --- a/.github/workflows/rocketzone-tests.yml +++ b/.github/workflows/rocketzone-tests.yml @@ -13,7 +13,7 @@ jobs: with: go-version: 1.14 id: go - + # checkout relayer - name: checkout relayer uses: actions/checkout@v2 @@ -28,4 +28,4 @@ jobs: # run tests - name: run rocketzone tests - run: TEST_DEBUG=true make test-rocketzone + run: make test-rocketzone From 0ae8e4141149c278b7e72c06058d6f21c276a9f5 Mon Sep 17 00:00:00 2001 From: Marko Baricevic Date: Mon, 25 May 2020 17:21:23 +0200 Subject: [PATCH 03/17] remove cover and add -race --- Makefile | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Makefile b/Makefile index 513df3a81..e5f20da8e 100644 --- a/Makefile +++ b/Makefile @@ -39,22 +39,22 @@ install: go.sum # Tests / CI ############################################################################### test: - @TEST_DEBUG=true go test -mod=readonly -v -coverprofile coverage.out ./test/... + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... test-gaia: - @TEST_DEBUG=true go test -mod=readonly -v -coverprofile coverage.out ./test/... -run TestGaia* + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestGaia* test-mtd: - @TEST_DEBUG=true go test -mod=readonly -v -coverprofile coverage.out ./test/... -run TestMtd* + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestMtd* test-rocketzone: - @TEST_DEBUG=true go test -mod=readonly -v -coverprofile coverage.out ./test/... -run TestRocket* + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestRocket* test-agoric: - @TEST_DEBUG=true go test -mod=readonly -v -coverprofile coverage.out ./test/... -run TestAgoric* + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestAgoric* test-coco: - @TEST_DEBUG=true go test -mod=mod -v -coverprofile coverage.out ./test/... -run TestCoCo* + @TEST_DEBUG=true go test -mod=mod -v -race ./test/... -run TestCoCo* coverage: @echo "viewing test coverage..." From 6919f2a81f849dc304ab785bf06ba2a93395ff76 Mon Sep 17 00:00:00 2001 From: Marko Baricevic Date: Tue, 26 May 2020 10:52:17 +0200 Subject: [PATCH 04/17] fully fix linting --- Makefile | 4 +- relayer/chain.go | 180 +++++++++++++++++++-------------------- relayer/channel-tx.go | 118 ++++++++++++------------- relayer/client-tx.go | 26 +++--- relayer/connection-tx.go | 72 ++++++++-------- relayer/faucet.go | 58 ++++++------- relayer/ics24.go | 56 ++++++------ relayer/packet-tx.go | 46 +++++----- relayer/pathEnd.go | 110 ++++++++++++------------ 9 files changed, 335 insertions(+), 335 deletions(-) diff --git a/Makefile b/Makefile index e5f20da8e..631754b2a 100644 --- a/Makefile +++ b/Makefile @@ -61,11 +61,11 @@ coverage: @go tool cover --html=coverage.out lint: - @GO111MODULE=on golangci-lint run + @golangci-lint run @find . -name '*.go' -type f -not -path "*.git*" | xargs gofmt -d -s @go mod verify -.PHONY: install build ci-lint coverage clean +.PHONY: install build lint coverage clean # TODO: Port reproducable build scripts from gaia for relayer # TODO: Full tested and working releases diff --git a/relayer/chain.go b/relayer/chain.go index 4c02927fa..ec9790599 100644 --- a/relayer/chain.go +++ b/relayer/chain.go @@ -59,29 +59,29 @@ type Chain struct { } // ListenRPCEmitJSON listens for tx and block events from a chain and outputs them as JSON to stdout -func (src *Chain) ListenRPCEmitJSON(tx, block, data bool) func() { +func (c *Chain) ListenRPCEmitJSON(tx, block, data bool) func() { doneChan := make(chan struct{}) - go src.listenLoop(doneChan, tx, block, data) + go c.listenLoop(doneChan, tx, block, data) return func() { doneChan <- struct{}{} } } -func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { +func (c *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { // Subscribe to source chain - if err := src.Start(); err != nil { - src.Error(err) + if err := c.Start(); err != nil { + c.Error(err) return } - srcTxEvents, srcTxCancel, err := src.Subscribe(txEvents) + srcTxEvents, srcTxCancel, err := c.Subscribe(txEvents) if err != nil { - src.Error(err) + c.Error(err) return } defer srcTxCancel() - srcBlockEvents, srcBlockCancel, err := src.Subscribe(blEvents) + srcBlockEvents, srcBlockCancel, err := c.Subscribe(blEvents) if err != nil { - src.Error(err) + c.Error(err) return } defer srcBlockCancel() @@ -101,7 +101,7 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { mar = srcMsg.Events } if byt, err = json.Marshal(mar); err != nil { - src.Error(err) + c.Error(err) } fmt.Println(string(byt)) case srcMsg := <-srcBlockEvents: @@ -114,7 +114,7 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { mar = srcMsg.Events } if byt, err = json.Marshal(mar); err != nil { - src.Error(err) + c.Error(err) } fmt.Println(string(byt)) case <-doneChan: @@ -126,38 +126,38 @@ func (src *Chain) listenLoop(doneChan chan struct{}, tx, block, data bool) { // Init initializes the pieces of a chain that aren't set when it parses a config // NOTE: All validation of the chain should happen here. -func (src *Chain) Init(homePath string, cdc *codecstd.Codec, amino *aminocodec.Codec, +func (c *Chain) Init(homePath string, cdc *codecstd.Codec, amino *aminocodec.Codec, timeout time.Duration, debug bool) error { - keybase, err := keys.New(src.ChainID, "test", keysDir(homePath, src.ChainID), nil) + keybase, err := keys.New(c.ChainID, "test", keysDir(homePath, c.ChainID), nil) if err != nil { return err } - client, err := newRPCClient(src.RPCAddr, timeout) + client, err := newRPCClient(c.RPCAddr, timeout) if err != nil { return err } - _, err = sdk.ParseDecCoins(src.GasPrices) + _, err = sdk.ParseDecCoins(c.GasPrices) if err != nil { return err } - _, err = time.ParseDuration(src.TrustingPeriod) + _, err = time.ParseDuration(c.TrustingPeriod) if err != nil { - return fmt.Errorf("failed to parse trusting period (%s) for chain %s", src.TrustingPeriod, src.ChainID) + return fmt.Errorf("failed to parse trusting period (%s) for chain %s", c.TrustingPeriod, c.ChainID) } - src.Keybase = keybase - src.Client = client - src.Cdc = newContextualStdCodec(cdc, src.UseSDKContext) - src.Amino = newContextualAminoCodec(amino, src.UseSDKContext) + c.Keybase = keybase + c.Client = client + c.Cdc = newContextualStdCodec(cdc, c.UseSDKContext) + c.Amino = newContextualAminoCodec(amino, c.UseSDKContext) RegisterCodec(amino) - src.HomePath = homePath - src.logger = defaultChainLogger() - src.timeout = timeout - src.debug = debug - src.faucetAddrs = make(map[string]time.Time) + c.HomePath = homePath + c.logger = defaultChainLogger() + c.timeout = timeout + c.debug = debug + c.faucetAddrs = make(map[string]time.Time) return nil } @@ -166,8 +166,8 @@ func defaultChainLogger() log.Logger { } // KeyExists returns true if there is a specified key in chain's keybase -func (src *Chain) KeyExists(name string) bool { - k, err := src.Keybase.Key(name) +func (c *Chain) KeyExists(name string) bool { + k, err := c.Keybase.Key(name) if err != nil { return false } @@ -175,14 +175,14 @@ func (src *Chain) KeyExists(name string) bool { return k.GetName() == name } -func (src *Chain) getGasPrices() sdk.DecCoins { - gp, _ := sdk.ParseDecCoins(src.GasPrices) +func (c *Chain) getGasPrices() sdk.DecCoins { + gp, _ := sdk.ParseDecCoins(c.GasPrices) return gp } // GetTrustingPeriod returns the trusting period for the chain -func (src *Chain) GetTrustingPeriod() time.Duration { - tp, _ := time.ParseDuration(src.TrustingPeriod) +func (c *Chain) GetTrustingPeriod() time.Duration { + tp, _ := time.ParseDuration(c.TrustingPeriod) return tp } @@ -203,72 +203,72 @@ func newRPCClient(addr string, timeout time.Duration) (*rpchttp.HTTP, error) { } // SendMsg wraps the msg in a stdtx, signs and sends it -func (src *Chain) SendMsg(datagram sdk.Msg) (sdk.TxResponse, error) { - return src.SendMsgs([]sdk.Msg{datagram}) +func (c *Chain) SendMsg(datagram sdk.Msg) (sdk.TxResponse, error) { + return c.SendMsgs([]sdk.Msg{datagram}) } // SendMsgs wraps the msgs in a stdtx, signs and sends it -func (src *Chain) SendMsgs(datagrams []sdk.Msg) (res sdk.TxResponse, err error) { +func (c *Chain) SendMsgs(datagrams []sdk.Msg) (res sdk.TxResponse, err error) { var out []byte - if out, err = src.BuildAndSignTx(datagrams); err != nil { + if out, err = c.BuildAndSignTx(datagrams); err != nil { return res, err } - return src.BroadcastTxCommit(out) + return c.BroadcastTxCommit(out) } // BuildAndSignTx takes messages and builds, signs and marshals a sdk.Tx to prepare it for broadcast -func (src *Chain) BuildAndSignTx(msgs []sdk.Msg) ([]byte, error) { - done := src.UseSDKContext() +func (c *Chain) BuildAndSignTx(msgs []sdk.Msg) ([]byte, error) { + done := c.UseSDKContext() defer done() // Fetch account and sequence numbers for the account - acc, err := auth.NewAccountRetriever(src.Cdc, src).GetAccount(src.MustGetAddress()) + acc, err := auth.NewAccountRetriever(c.Cdc, c).GetAccount(c.MustGetAddress()) if err != nil { return nil, err } - ctx := sdkCtx.CLIContext{Client: src.Client} + ctx := sdkCtx.CLIContext{Client: c.Client} txBldr := auth.NewTxBuilder( - auth.DefaultTxEncoder(src.Amino.Codec), acc.GetAccountNumber(), - acc.GetSequence(), src.Gas, src.GasAdjustment, true, src.ChainID, - src.Memo, sdk.NewCoins(), src.getGasPrices()).WithKeybase(src.Keybase) - if src.GasAdjustment > 0 { + auth.DefaultTxEncoder(c.Amino.Codec), acc.GetAccountNumber(), + acc.GetSequence(), c.Gas, c.GasAdjustment, true, c.ChainID, + c.Memo, sdk.NewCoins(), c.getGasPrices()).WithKeybase(c.Keybase) + if c.GasAdjustment > 0 { txBldr, err = authclient.EnrichWithGas(txBldr, ctx, msgs) if err != nil { return nil, err } } - return txBldr.BuildAndSign(src.Key, ckeys.DefaultKeyPass, msgs) + return txBldr.BuildAndSign(c.Key, ckeys.DefaultKeyPass, msgs) } // BroadcastTxCommit takes the marshaled transaction bytes and broadcasts them -func (src *Chain) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { - return sdkCtx.CLIContext{Client: src.Client}.BroadcastTxCommit(txBytes) +func (c *Chain) BroadcastTxCommit(txBytes []byte) (sdk.TxResponse, error) { + return sdkCtx.CLIContext{Client: c.Client}.BroadcastTxCommit(txBytes) } // Log takes a string and logs the data -func (src *Chain) Log(s string) { - src.logger.Info(s) +func (c *Chain) Log(s string) { + c.logger.Info(s) } // Error takes an error, wraps it in the chainID and logs the error -func (src *Chain) Error(err error) { - src.logger.Error(fmt.Sprintf("%s: err(%s)", src.ChainID, err.Error())) +func (c *Chain) Error(err error) { + c.logger.Error(fmt.Sprintf("%s: err(%s)", c.ChainID, err.Error())) } // Start the client service -func (src *Chain) Start() error { - return src.Client.Start() +func (c *Chain) Start() error { + return c.Client.Start() } // Subscribe returns channel of events given a query -func (src *Chain) Subscribe(query string) (<-chan ctypes.ResultEvent, context.CancelFunc, error) { +func (c *Chain) Subscribe(query string) (<-chan ctypes.ResultEvent, context.CancelFunc, error) { suffix, err := GenerateRandomString(8) if err != nil { return nil, nil, err } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - eventChan, err := src.Client.Subscribe(ctx, fmt.Sprintf("%s-subscriber-%s", src.ChainID, suffix), query, 1000) + eventChan, err := c.Client.Subscribe(ctx, fmt.Sprintf("%s-subscriber-%s", c.ChainID, suffix), query, 1000) return eventChan, cancel, err } @@ -282,24 +282,24 @@ func liteDir(home string) string { } // GetAddress returns the sdk.AccAddress associated with the configred key -func (src *Chain) GetAddress() (sdk.AccAddress, error) { - if src.address != nil { - return src.address, nil +func (c *Chain) GetAddress() (sdk.AccAddress, error) { + if c.address != nil { + return c.address, nil } - // Signing key for src chain - srcAddr, err := src.Keybase.Key(src.Key) + // Signing key for c chain + srcAddr, err := c.Keybase.Key(c.Key) if err != nil { return nil, err } - src.address = srcAddr.GetAddress() - return src.address, nil + c.address = srcAddr.GetAddress() + return c.address, nil } // MustGetAddress used for brevity -func (src *Chain) MustGetAddress() sdk.AccAddress { - srcAddr, err := src.GetAddress() +func (c *Chain) MustGetAddress() sdk.AccAddress { + srcAddr, err := c.GetAddress() if err != nil { panic(err) } @@ -309,7 +309,7 @@ func (src *Chain) MustGetAddress() sdk.AccAddress { var sdkContextMutex sync.Mutex // UseSDKContext uses a custom Bech32 account prefix and returns a restore func -func (src *Chain) UseSDKContext() func() { +func (c *Chain) UseSDKContext() func() { // Ensure we're the only one using the global context. sdkContextMutex.Lock() defer sdkContextMutex.Unlock() @@ -319,7 +319,7 @@ func (src *Chain) UseSDKContext() func() { pubaccount := sdkConf.GetBech32AccountPubPrefix() // Mutate the sdkConf - sdkConf.SetBech32PrefixForAccount(src.AccountPrefix, src.AccountPrefix+"pub") + sdkConf.SetBech32PrefixForAccount(c.AccountPrefix, c.AccountPrefix+"pub") // Return a function that resets and unlocks. return func() { @@ -330,17 +330,17 @@ func (src *Chain) UseSDKContext() func() { } } -func (src *Chain) String() string { - done := src.UseSDKContext() +func (c *Chain) String() string { + done := c.UseSDKContext() defer done() - out, _ := json.Marshal(src) + out, _ := json.Marshal(c) return string(out) } // Update returns a new chain with updated values -func (src *Chain) Update(key, value string) (out *Chain, err error) { - out = src +func (c *Chain) Update(key, value string) (out *Chain, err error) { + out = c switch key { case "key": out.Key = value @@ -384,7 +384,7 @@ func (src *Chain) Update(key, value string) (out *Chain, err error) { // Print fmt.Printlns the json or yaml representation of whatever is passed in // CONTRACT: The cmd calling this function needs to have the "json" and "indent" flags set // TODO: better "text" printing here would be a nice to have -func (src *Chain) Print(toPrint interface{}, text, indent bool) error { +func (c *Chain) Print(toPrint interface{}, text, indent bool) error { var ( out []byte err error @@ -394,12 +394,12 @@ func (src *Chain) Print(toPrint interface{}, text, indent bool) error { case indent && text: return fmt.Errorf("must pass either indent or text, not both") case indent: - out, err = src.Amino.MarshalJSONIndent(toPrint, "", " ") + out, err = c.Amino.MarshalJSONIndent(toPrint, "", " ") case text: // TODO: This isn't really a good option, out = []byte(fmt.Sprintf("%v", toPrint)) default: - out, err = src.Amino.MarshalJSON(toPrint) + out, err = c.Amino.MarshalJSON(toPrint) } if err != nil { @@ -411,19 +411,19 @@ func (src *Chain) Print(toPrint interface{}, text, indent bool) error { } // SendAndPrint sends a transaction and prints according to the passed args -func (src *Chain) SendAndPrint(txs []sdk.Msg, text, indent bool) (err error) { - if src.debug { - if err = src.Print(txs, text, indent); err != nil { +func (c *Chain) SendAndPrint(txs []sdk.Msg, text, indent bool) (err error) { + if c.debug { + if err = c.Print(txs, text, indent); err != nil { return err } } // SendAndPrint sends the transaction with printing options from the CLI - res, err := src.SendMsgs(txs) + res, err := c.SendMsgs(txs) if err != nil { return err } - return src.Print(res, text, indent) + return c.Print(res, text, indent) } @@ -465,15 +465,15 @@ func (c Chains) Gets(chainIDs ...string) (map[string]*Chain, error) { } // GetRPCPort returns the port configured for the chain -func (src *Chain) GetRPCPort() string { - u, _ := url.Parse(src.RPCAddr) +func (c *Chain) GetRPCPort() string { + u, _ := url.Parse(c.RPCAddr) return u.Port() } // CreateTestKey creates a key for test chain -func (src *Chain) CreateTestKey() error { - if src.KeyExists(src.Key) { - return fmt.Errorf("key %s exists for chain %s", src.ChainID, src.Key) +func (c *Chain) CreateTestKey() error { + if c.KeyExists(c.Key) { + return fmt.Errorf("key %s exists for chain %s", c.ChainID, c.Key) } mnemonic, err := CreateMnemonic() @@ -481,7 +481,7 @@ func (src *Chain) CreateTestKey() error { return err } - _, err = src.Keybase.NewAccount(src.Key, mnemonic, "", hd.CreateHDPath(118, 0, 0).String(), hd.Secp256k1) + _, err = c.Keybase.NewAccount(c.Key, mnemonic, "", hd.CreateHDPath(118, 0, 0).String(), hd.Secp256k1) return err } @@ -499,13 +499,13 @@ func CreateMnemonic() (string, error) { } // GetTimeout returns the chain's configured timeout -func (src *Chain) GetTimeout() time.Duration { - return src.timeout +func (c *Chain) GetTimeout() time.Duration { + return c.timeout } // StatusErr returns err unless the chain is ready to go -func (src *Chain) StatusErr() error { - stat, err := src.Client.Status() +func (c *Chain) StatusErr() error { + stat, err := c.Client.Status() switch { case err != nil: return err diff --git a/relayer/channel-tx.go b/relayer/channel-tx.go index 5792c7abd..e4f1ac44b 100644 --- a/relayer/channel-tx.go +++ b/relayer/channel-tx.go @@ -10,7 +10,7 @@ import ( // CreateChannel runs the channel creation messages on timeout until they pass // TODO: add max retries or something to this function -func (src *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) error { +func (c *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) error { var order ibctypes.Order if ordered { order = ibctypes.ORDERED @@ -21,7 +21,7 @@ func (src *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) erro ticker := time.NewTicker(to) failures := 0 for ; true; <-ticker.C { - chanSteps, err := src.CreateChannelStep(dst, order) + chanSteps, err := c.CreateChannelStep(dst, order) if err != nil { return err } @@ -30,21 +30,21 @@ func (src *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) erro break } - chanSteps.Send(src, dst) + chanSteps.Send(c, dst) switch { // In the case of success and this being the last transaction // debug logging, log created connection and break case chanSteps.success && chanSteps.last: - chans, err := QueryChannelPair(src, dst, 0, 0) + chans, err := QueryChannelPair(c, dst, 0, 0) if err != nil { return err } - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } - src.Log(fmt.Sprintf("★ Channel created: [%s]chan{%s}port{%s} -> [%s]chan{%s}port{%s}", - src.ChainID, src.PathEnd.ChannelID, src.PathEnd.PortID, + c.Log(fmt.Sprintf("★ Channel created: [%s]chan{%s}port{%s} -> [%s]chan{%s}port{%s}", + c.ChainID, c.PathEnd.ChannelID, c.PathEnd.PortID, dst.ChainID, dst.PathEnd.ChannelID, dst.PathEnd.PortID)) return nil // In the case of success, reset the failures counter @@ -56,7 +56,7 @@ func (src *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) erro failures++ if failures > 2 { return fmt.Errorf("! Channel failed: [%s]chan{%s}port{%s} -> [%s]chan{%s}port{%s}", - src.ChainID, src.PathEnd.ChannelID, src.PathEnd.PortID, + c.ChainID, c.PathEnd.ChannelID, c.PathEnd.PortID, dst.ChainID, dst.PathEnd.ChannelID, dst.PathEnd.PortID) } } @@ -68,26 +68,26 @@ func (src *Chain) CreateChannel(dst *Chain, ordered bool, to time.Duration) erro // CreateChannelStep returns the next set of messages for creating a channel with given // identifiers between chains src and dst. If the handshake hasn't started, then CreateChannelStep // will begin the handshake on the src chain -func (src *Chain) CreateChannelStep(dst *Chain, ordering ibctypes.Order) (*RelayMsgs, error) { +func (c *Chain) CreateChannelStep(dst *Chain, ordering ibctypes.Order) (*RelayMsgs, error) { var ( out = &RelayMsgs{Src: []sdk.Msg{}, Dst: []sdk.Msg{}, last: false} - scid, dcid = src.ChainID, dst.ChainID + scid, dcid = c.ChainID, dst.ChainID ) - if err := src.PathEnd.Validate(); err != nil { - return nil, src.ErrCantSetPath(err) + if err := c.PathEnd.Validate(); err != nil { + return nil, c.ErrCantSetPath(err) } if err := dst.PathEnd.Validate(); err != nil { return nil, dst.ErrCantSetPath(err) } - hs, err := UpdatesWithHeaders(src, dst) + hs, err := UpdatesWithHeaders(c, dst) if err != nil { return nil, err } - chans, err := QueryChannelPair(src, dst, hs[scid].Height-1, hs[dcid].Height-1) + chans, err := QueryChannelPair(c, dst, hs[scid].Height-1, hs[dcid].Height-1) if err != nil { return nil, err } @@ -95,37 +95,37 @@ func (src *Chain) CreateChannelStep(dst *Chain, ordering ibctypes.Order) (*Relay switch { // Handshake hasn't been started on src or dst, relay `chanOpenInit` to src case chans[scid].Channel.State == ibctypes.UNINITIALIZED && chans[dcid].Channel.State == ibctypes.UNINITIALIZED: - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.ChanInit(dst.PathEnd, src.MustGetAddress()), + c.PathEnd.ChanInit(dst.PathEnd, c.MustGetAddress()), ) // Handshake has started on dst (1 step done), relay `chanOpenTry` and `updateClient` to src case chans[scid].Channel.State == ibctypes.UNINITIALIZED && chans[dcid].Channel.State == ibctypes.INIT: - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ChanTry(dst.PathEnd, chans[dcid], src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ChanTry(dst.PathEnd, chans[dcid], c.MustGetAddress()), ) // Handshake has started on src (1 step done), relay `chanOpenTry` and `updateClient` to dst case chans[scid].Channel.State == ibctypes.INIT && chans[dcid].Channel.State == ibctypes.UNINITIALIZED: if dst.debug { - logChannelStates(dst, src, chans) + logChannelStates(dst, c, chans) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), - dst.PathEnd.ChanTry(src.PathEnd, chans[scid], dst.MustGetAddress()), + dst.PathEnd.ChanTry(c.PathEnd, chans[scid], dst.MustGetAddress()), ) // Handshake has started on src (2 steps done), relay `chanOpenAck` and `updateClient` to dst case chans[scid].Channel.State == ibctypes.TRYOPEN && chans[dcid].Channel.State == ibctypes.INIT: if dst.debug { - logChannelStates(dst, src, chans) + logChannelStates(dst, c, chans) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), @@ -134,29 +134,29 @@ func (src *Chain) CreateChannelStep(dst *Chain, ordering ibctypes.Order) (*Relay // Handshake has started on dst (2 steps done), relay `chanOpenAck` and `updateClient` to src case chans[scid].Channel.State == ibctypes.INIT && chans[dcid].Channel.State == ibctypes.TRYOPEN: - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ChanAck(chans[dcid], src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ChanAck(chans[dcid], c.MustGetAddress()), ) // Handshake has confirmed on dst (3 steps done), relay `chanOpenConfirm` and `updateClient` to src case chans[scid].Channel.State == ibctypes.TRYOPEN && chans[dcid].Channel.State == ibctypes.OPEN: - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ChanConfirm(chans[dcid], src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ChanConfirm(chans[dcid], c.MustGetAddress()), ) out.last = true // Handshake has confirmed on src (3 steps done), relay `chanOpenConfirm` and `updateClient` to dst case chans[scid].Channel.State == ibctypes.OPEN && chans[dcid].Channel.State == ibctypes.TRYOPEN: if dst.debug { - logChannelStates(dst, src, chans) + logChannelStates(dst, c, chans) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), @@ -170,11 +170,11 @@ func (src *Chain) CreateChannelStep(dst *Chain, ordering ibctypes.Order) (*Relay // CloseChannel runs the channel closing messages on timeout until they pass // TODO: add max retries or something to this function -func (src *Chain) CloseChannel(dst *Chain, to time.Duration) error { +func (c *Chain) CloseChannel(dst *Chain, to time.Duration) error { ticker := time.NewTicker(to) for ; true; <-ticker.C { - closeSteps, err := src.CloseChannelStep(dst) + closeSteps, err := c.CloseChannelStep(dst) if err != nil { return err } @@ -183,16 +183,16 @@ func (src *Chain) CloseChannel(dst *Chain, to time.Duration) error { break } - if closeSteps.Send(src, dst); closeSteps.success && closeSteps.last { - chans, err := QueryChannelPair(src, dst, 0, 0) + if closeSteps.Send(c, dst); closeSteps.success && closeSteps.last { + chans, err := QueryChannelPair(c, dst, 0, 0) if err != nil { return err } - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } - src.Log(fmt.Sprintf("★ Closed channel between [%s]chan{%s}port{%s} -> [%s]chan{%s}port{%s}", - src.ChainID, src.PathEnd.ChannelID, src.PathEnd.PortID, + c.Log(fmt.Sprintf("★ Closed channel between [%s]chan{%s}port{%s} -> [%s]chan{%s}port{%s}", + c.ChainID, c.PathEnd.ChannelID, c.PathEnd.PortID, dst.ChainID, dst.PathEnd.ChannelID, dst.PathEnd.PortID)) break } @@ -203,46 +203,46 @@ func (src *Chain) CloseChannel(dst *Chain, to time.Duration) error { // CloseChannelStep returns the next set of messages for closing a channel with given // identifiers between chains src and dst. If the closing handshake hasn't started, then CloseChannelStep // will begin the handshake on the src chain -func (src *Chain) CloseChannelStep(dst *Chain) (*RelayMsgs, error) { +func (c *Chain) CloseChannelStep(dst *Chain) (*RelayMsgs, error) { var ( out = &RelayMsgs{Src: []sdk.Msg{}, Dst: []sdk.Msg{}, last: false} - scid, dcid = src.ChainID, dst.ChainID + scid, dcid = c.ChainID, dst.ChainID ) - if err := src.PathEnd.Validate(); err != nil { - return nil, src.ErrCantSetPath(err) + if err := c.PathEnd.Validate(); err != nil { + return nil, c.ErrCantSetPath(err) } if err := dst.PathEnd.Validate(); err != nil { return nil, dst.ErrCantSetPath(err) } - hs, err := UpdatesWithHeaders(src, dst) + hs, err := UpdatesWithHeaders(c, dst) if err != nil { return nil, err } - chans, err := QueryChannelPair(src, dst, hs[scid].Height-1, hs[dcid].Height-1) + chans, err := QueryChannelPair(c, dst, hs[scid].Height-1, hs[dcid].Height-1) if err != nil { return nil, err } - logChannelStates(src, dst, chans) + logChannelStates(c, dst, chans) switch { // Closing handshake has not started, relay `updateClient` and `chanCloseInit` to src or dst according // to the channel state case chans[scid].Channel.State != ibctypes.CLOSED && chans[dcid].Channel.State != ibctypes.CLOSED: if chans[scid].Channel.State != ibctypes.UNINITIALIZED { - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ChanCloseInit(src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ChanCloseInit(c.MustGetAddress()), ) } else if chans[dcid].Channel.State != ibctypes.UNINITIALIZED { if dst.debug { - logChannelStates(dst, src, chans) + logChannelStates(dst, c, chans) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), @@ -254,7 +254,7 @@ func (src *Chain) CloseChannelStep(dst *Chain) (*RelayMsgs, error) { case chans[scid].Channel.State == ibctypes.CLOSED && chans[dcid].Channel.State != ibctypes.CLOSED: if chans[dcid].Channel.State != ibctypes.UNINITIALIZED { if dst.debug { - logChannelStates(dst, src, chans) + logChannelStates(dst, c, chans) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), @@ -266,12 +266,12 @@ func (src *Chain) CloseChannelStep(dst *Chain) (*RelayMsgs, error) { // Closing handshake has started on dst, relay `updateClient` and `chanCloseConfirm` to src case chans[dcid].Channel.State == ibctypes.CLOSED && chans[scid].Channel.State != ibctypes.CLOSED: if chans[scid].Channel.State != ibctypes.UNINITIALIZED { - if src.debug { - logChannelStates(src, dst, chans) + if c.debug { + logChannelStates(c, dst, chans) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ChanCloseConfirm(chans[dcid], src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ChanCloseConfirm(chans[dcid], c.MustGetAddress()), ) out.last = true } diff --git a/relayer/client-tx.go b/relayer/client-tx.go index 4586ad882..fa81f80aa 100644 --- a/relayer/client-tx.go +++ b/relayer/client-tx.go @@ -8,43 +8,43 @@ import ( ) // CreateClients creates clients for src on dst and dst on src given the configured paths -func (src *Chain) CreateClients(dst *Chain) (err error) { +func (c *Chain) CreateClients(dst *Chain) (err error) { clients := &RelayMsgs{Src: []sdk.Msg{}, Dst: []sdk.Msg{}} - // Create client for dst on src if it doesn't exist + // Create client for dst on c if it doesn't exist var srcCs, dstCs *clientTypes.StateResponse - if srcCs, err = src.QueryClientState(); err != nil { + if srcCs, err = c.QueryClientState(); err != nil { return err } else if srcCs == nil { dstH, err := dst.UpdateLiteWithHeader() if err != nil { return err } - if src.debug { - src.logCreateClient(dst, dstH.GetHeight()) + if c.debug { + c.logCreateClient(dst, dstH.GetHeight()) } - clients.Src = append(clients.Src, src.PathEnd.CreateClient(dstH, dst.GetTrustingPeriod(), src.MustGetAddress())) + clients.Src = append(clients.Src, c.PathEnd.CreateClient(dstH, dst.GetTrustingPeriod(), c.MustGetAddress())) } - // Create client for src on dst if it doesn't exist + // Create client for c on dst if it doesn't exist if dstCs, err = dst.QueryClientState(); err != nil { return err } else if dstCs == nil { - srcH, err := src.UpdateLiteWithHeader() + srcH, err := c.UpdateLiteWithHeader() if err != nil { return err } if dst.debug { - dst.logCreateClient(src, srcH.GetHeight()) + dst.logCreateClient(c, srcH.GetHeight()) } - clients.Dst = append(clients.Dst, dst.PathEnd.CreateClient(srcH, src.GetTrustingPeriod(), dst.MustGetAddress())) + clients.Dst = append(clients.Dst, dst.PathEnd.CreateClient(srcH, c.GetTrustingPeriod(), dst.MustGetAddress())) } // Send msgs to both chains if clients.Ready() { - if clients.Send(src, dst); clients.success { - src.Log(fmt.Sprintf("★ Clients created: [%s]client(%s) and [%s]client(%s)", - src.ChainID, src.PathEnd.ClientID, dst.ChainID, dst.PathEnd.ClientID)) + if clients.Send(c, dst); clients.success { + c.Log(fmt.Sprintf("★ Clients created: [%s]client(%s) and [%s]client(%s)", + c.ChainID, c.PathEnd.ClientID, dst.ChainID, dst.PathEnd.ClientID)) } } diff --git a/relayer/connection-tx.go b/relayer/connection-tx.go index 0b9bba7bb..2945f1cfd 100644 --- a/relayer/connection-tx.go +++ b/relayer/connection-tx.go @@ -10,11 +10,11 @@ import ( // CreateConnection runs the connection creation messages on timeout until they pass // TODO: add max retries or something to this function -func (src *Chain) CreateConnection(dst *Chain, to time.Duration) error { +func (c *Chain) CreateConnection(dst *Chain, to time.Duration) error { ticker := time.NewTicker(to) failed := 0 for ; true; <-ticker.C { - connSteps, err := src.CreateConnectionStep(dst) + connSteps, err := c.CreateConnectionStep(dst) if err != nil { return err } @@ -23,22 +23,22 @@ func (src *Chain) CreateConnection(dst *Chain, to time.Duration) error { break } - connSteps.Send(src, dst) + connSteps.Send(c, dst) switch { // In the case of success and this being the last transaction // debug logging, log created connection and break case connSteps.success && connSteps.last: - if src.debug { - conns, err := QueryConnectionPair(src, dst, 0, 0) + if c.debug { + conns, err := QueryConnectionPair(c, dst, 0, 0) if err != nil { return err } - logConnectionStates(src, dst, conns) + logConnectionStates(c, dst, conns) } - src.Log(fmt.Sprintf("★ Connection created: [%s]client{%s}conn{%s} -> [%s]client{%s}conn{%s}", - src.ChainID, src.PathEnd.ClientID, src.PathEnd.ConnectionID, + c.Log(fmt.Sprintf("★ Connection created: [%s]client{%s}conn{%s} -> [%s]client{%s}conn{%s}", + c.ChainID, c.PathEnd.ClientID, c.PathEnd.ConnectionID, dst.ChainID, dst.PathEnd.ClientID, dst.PathEnd.ConnectionID)) return nil // In the case of success, reset the failures counter @@ -50,7 +50,7 @@ func (src *Chain) CreateConnection(dst *Chain, to time.Duration) error { failed++ if failed > 2 { return fmt.Errorf("! Connection failed: [%s]client{%s}conn{%s} -> [%s]client{%s}conn{%s}", - src.ChainID, src.PathEnd.ClientID, src.PathEnd.ConnectionID, + c.ChainID, c.PathEnd.ClientID, c.PathEnd.ConnectionID, dst.ChainID, dst.PathEnd.ClientID, dst.PathEnd.ConnectionID) } } @@ -62,35 +62,35 @@ func (src *Chain) CreateConnection(dst *Chain, to time.Duration) error { // CreateConnectionStep returns the next set of messags for creating a channel // with the given identifier between chains src and dst. If handshake hasn't started, // CreateConnetionStep will start the handshake on src -func (src *Chain) CreateConnectionStep(dst *Chain) (*RelayMsgs, error) { +func (c *Chain) CreateConnectionStep(dst *Chain) (*RelayMsgs, error) { out := &RelayMsgs{Src: []sdk.Msg{}, Dst: []sdk.Msg{}, last: false} - if err := src.PathEnd.Validate(); err != nil { - return nil, src.ErrCantSetPath(err) + if err := c.PathEnd.Validate(); err != nil { + return nil, c.ErrCantSetPath(err) } if err := dst.PathEnd.Validate(); err != nil { return nil, dst.ErrCantSetPath(err) } - hs, err := UpdatesWithHeaders(src, dst) + hs, err := UpdatesWithHeaders(c, dst) if err != nil { return nil, err } - scid, dcid := src.ChainID, dst.ChainID + scid, dcid := c.ChainID, dst.ChainID // Query Connection data from src and dst // NOTE: We query connection at height - 1 because of the way tendermint returns // proofs the commit for height n is contained in the header of height n + 1 - conn, err := QueryConnectionPair(src, dst, hs[scid].Height-1, hs[dcid].Height-1) + conn, err := QueryConnectionPair(c, dst, hs[scid].Height-1, hs[dcid].Height-1) if err != nil { return nil, err } // NOTE: We query connection at height - 1 because of the way tendermint returns // proofs the commit for height n is contained in the header of height n + 1 - cs, err := QueryClientStatePair(src, dst) + cs, err := QueryClientStatePair(c, dst) if err != nil { return nil, err } @@ -105,7 +105,7 @@ func (src *Chain) CreateConnectionStep(dst *Chain) (*RelayMsgs, error) { // NOTE: We query connection at height - 1 because of the way tendermint returns // proofs the commit for height n is contained in the header of height n + 1 - cons, err := QueryClientConsensusStatePair(src, dst, hs[scid].Height-1, hs[dcid].Height-1, srcConsH, dstConsH) + cons, err := QueryClientConsensusStatePair(c, dst, hs[scid].Height-1, hs[dcid].Height-1, srcConsH, dstConsH) if err != nil { return nil, err } @@ -113,35 +113,35 @@ func (src *Chain) CreateConnectionStep(dst *Chain) (*RelayMsgs, error) { switch { // Handshake hasn't been started on src or dst, relay `connOpenInit` to src case conn[scid].Connection.State == ibctypes.UNINITIALIZED && conn[dcid].Connection.State == ibctypes.UNINITIALIZED: - if src.debug { - logConnectionStates(src, dst, conn) + if c.debug { + logConnectionStates(c, dst, conn) } - out.Src = append(out.Src, src.PathEnd.ConnInit(dst.PathEnd, src.MustGetAddress())) + out.Src = append(out.Src, c.PathEnd.ConnInit(dst.PathEnd, c.MustGetAddress())) // Handshake has started on dst (1 stepdone), relay `connOpenTry` and `updateClient` on src case conn[scid].Connection.State == ibctypes.UNINITIALIZED && conn[dcid].Connection.State == ibctypes.INIT: - if src.debug { - logConnectionStates(src, dst, conn) + if c.debug { + logConnectionStates(c, dst, conn) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ConnTry(dst.PathEnd, conn[dcid], cons[dcid], dstConsH, src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ConnTry(dst.PathEnd, conn[dcid], cons[dcid], dstConsH, c.MustGetAddress()), ) // Handshake has started on src (1 step done), relay `connOpenTry` and `updateClient` on dst case conn[scid].Connection.State == ibctypes.INIT && conn[dcid].Connection.State == ibctypes.UNINITIALIZED: if dst.debug { - logConnectionStates(dst, src, conn) + logConnectionStates(dst, c, conn) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), - dst.PathEnd.ConnTry(src.PathEnd, conn[scid], cons[scid], srcConsH, dst.MustGetAddress()), + dst.PathEnd.ConnTry(c.PathEnd, conn[scid], cons[scid], srcConsH, dst.MustGetAddress()), ) // Handshake has started on src end (2 steps done), relay `connOpenAck` and `updateClient` to dst end case conn[scid].Connection.State == ibctypes.TRYOPEN && conn[dcid].Connection.State == ibctypes.INIT: if dst.debug { - logConnectionStates(dst, src, conn) + logConnectionStates(dst, c, conn) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), @@ -150,29 +150,29 @@ func (src *Chain) CreateConnectionStep(dst *Chain) (*RelayMsgs, error) { // Handshake has started on dst end (2 steps done), relay `connOpenAck` and `updateClient` to src end case conn[scid].Connection.State == ibctypes.INIT && conn[dcid].Connection.State == ibctypes.TRYOPEN: - if src.debug { - logConnectionStates(src, dst, conn) + if c.debug { + logConnectionStates(c, dst, conn) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ConnAck(conn[dcid], cons[dcid], dstConsH, src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ConnAck(conn[dcid], cons[dcid], dstConsH, c.MustGetAddress()), ) // Handshake has confirmed on dst (3 steps done), relay `connOpenConfirm` and `updateClient` to src end case conn[scid].Connection.State == ibctypes.TRYOPEN && conn[dcid].Connection.State == ibctypes.OPEN: - if src.debug { - logConnectionStates(src, dst, conn) + if c.debug { + logConnectionStates(c, dst, conn) } out.Src = append(out.Src, - src.PathEnd.UpdateClient(hs[dcid], src.MustGetAddress()), - src.PathEnd.ConnConfirm(conn[dcid], src.MustGetAddress()), + c.PathEnd.UpdateClient(hs[dcid], c.MustGetAddress()), + c.PathEnd.ConnConfirm(conn[dcid], c.MustGetAddress()), ) out.last = true // Handshake has confirmed on src (3 steps done), relay `connOpenConfirm` and `updateClient` to dst end case conn[scid].Connection.State == ibctypes.OPEN && conn[dcid].Connection.State == ibctypes.TRYOPEN: if dst.debug { - logConnectionStates(dst, src, conn) + logConnectionStates(dst, c, conn) } out.Dst = append(out.Dst, dst.PathEnd.UpdateClient(hs[scid], dst.MustGetAddress()), diff --git a/relayer/faucet.go b/relayer/faucet.go index ee2d72603..5c3e75e67 100644 --- a/relayer/faucet.go +++ b/relayer/faucet.go @@ -14,49 +14,49 @@ import ( ) // SendMsgWithKey allows the user to specify which relayer key will sign the message -func (src *Chain) SendMsgWithKey(datagram sdk.Msg, keyName string) (res sdk.TxResponse, err error) { +func (c *Chain) SendMsgWithKey(datagram sdk.Msg, keyName string) (res sdk.TxResponse, err error) { var out []byte - if out, err = src.BuildAndSignTxWithKey([]sdk.Msg{datagram}, keyName); err != nil { + if out, err = c.BuildAndSignTxWithKey([]sdk.Msg{datagram}, keyName); err != nil { return res, err } - return src.BroadcastTxCommit(out) + return c.BroadcastTxCommit(out) } // BuildAndSignTxWithKey allows the user to specify which relayer key will sign the message -func (src *Chain) BuildAndSignTxWithKey(datagram []sdk.Msg, keyName string) ([]byte, error) { +func (c *Chain) BuildAndSignTxWithKey(datagram []sdk.Msg, keyName string) ([]byte, error) { // Fetch account and sequence numbers for the account - info, err := src.Keybase.Key(keyName) + info, err := c.Keybase.Key(keyName) if err != nil { return nil, err } - done := src.UseSDKContext() + done := c.UseSDKContext() defer done() - acc, err := auth.NewAccountRetriever(src.Cdc, src).GetAccount(info.GetAddress()) + acc, err := auth.NewAccountRetriever(c.Cdc, c).GetAccount(info.GetAddress()) if err != nil { return nil, err } return auth.NewTxBuilder( - auth.DefaultTxEncoder(src.Amino.Codec), acc.GetAccountNumber(), - acc.GetSequence(), src.Gas, src.GasAdjustment, false, src.ChainID, - src.Memo, sdk.NewCoins(), src.getGasPrices()).WithKeybase(src.Keybase). + auth.DefaultTxEncoder(c.Amino.Codec), acc.GetAccountNumber(), + acc.GetSequence(), c.Gas, c.GasAdjustment, false, c.ChainID, + c.Memo, sdk.NewCoins(), c.getGasPrices()).WithKeybase(c.Keybase). BuildAndSign(info.GetName(), ckeys.DefaultKeyPass, datagram) } // FaucetHandler listens for addresses -func (src *Chain) FaucetHandler(fromKey sdk.AccAddress, amount sdk.Coin) func(w http.ResponseWriter, r *http.Request) { +func (c *Chain) FaucetHandler(fromKey sdk.AccAddress, amount sdk.Coin) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() - src.Log("handling faucet request...") + c.Log("handling faucet request...") byt, err := ioutil.ReadAll(r.Body) if err != nil { str := "Failed to read request body" - src.Error(fmt.Errorf("%s: %w", str, err)) + c.Error(fmt.Errorf("%s: %w", str, err)) respondWithError(w, http.StatusBadGateway, str) return } @@ -66,44 +66,44 @@ func (src *Chain) FaucetHandler(fromKey sdk.AccAddress, amount sdk.Coin) func(w switch { case err != nil: str := fmt.Sprintf("Failed to unmarshal request payload: %s", string(byt)) - src.Log(str) + c.Log(str) respondWithError(w, http.StatusBadRequest, str) return - case fr.ChainID != src.ChainID: - str := fmt.Sprintf("Invalid chain id: exp(%s) got(%s)", src.ChainID, fr.ChainID) - src.Log(str) + case fr.ChainID != c.ChainID: + str := fmt.Sprintf("Invalid chain id: exp(%s) got(%s)", c.ChainID, fr.ChainID) + c.Log(str) respondWithError(w, http.StatusBadRequest, str) return } - if wait, err := src.checkAddress(fr.Address); err != nil { - src.Log(fmt.Sprintf("%s hit rate limit, needs to wait %s", fr.Address, wait.String())) + if wait, err := c.checkAddress(fr.Address); err != nil { + c.Log(fmt.Sprintf("%s hit rate limit, needs to wait %s", fr.Address, wait.String())) respondWithError(w, http.StatusTooManyRequests, err.Error()) return } - done := src.UseSDKContext() + done := c.UseSDKContext() defer done() - if err := src.faucetSend(fromKey, fr.addr(), amount); err != nil { - src.Error(err) + if err := c.faucetSend(fromKey, fr.addr(), amount); err != nil { + c.Error(err) respondWithError(w, http.StatusInternalServerError, err.Error()) return } - src.Log(fmt.Sprintf("%s was sent %s successfully", fr.Address, amount.String())) + c.Log(fmt.Sprintf("%s was sent %s successfully", fr.Address, amount.String())) respondWithJSON(w, http.StatusCreated, success{Address: fr.Address, Amount: amount.String()}) } } -func (src *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coin) error { +func (c *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coin) error { // Set sdk config to use custom Bech32 account prefix - info, err := src.Keybase.KeyByAddress(fromAddr) + info, err := c.Keybase.KeyByAddress(fromAddr) if err != nil { return err } - res, err := src.SendMsgWithKey(bank.NewMsgSend(fromAddr, toAddr, sdk.NewCoins(amount)), info.GetName()) + res, err := c.SendMsgWithKey(bank.NewMsgSend(fromAddr, toAddr, sdk.NewCoins(amount)), info.GetName()) if err != nil { return fmt.Errorf("failed to send transaction: %w\n%s", err, res) } else if res.Code != 0 { @@ -112,9 +112,9 @@ func (src *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coin) e return nil } -func (src *Chain) checkAddress(addr string) (time.Duration, error) { +func (c *Chain) checkAddress(addr string) (time.Duration, error) { faucetTimeout := 5 * time.Minute - if val, ok := src.faucetAddrs[addr]; ok { + if val, ok := c.faucetAddrs[addr]; ok { sinceLastRequest := time.Since(val) if faucetTimeout > sinceLastRequest { wait := faucetTimeout - sinceLastRequest @@ -122,7 +122,7 @@ func (src *Chain) checkAddress(addr string) (time.Duration, error) { addr, faucetTimeout.String(), wait.String()) } } - src.faucetAddrs[addr] = time.Now() + c.faucetAddrs[addr] = time.Now() return 1 * time.Second, nil } diff --git a/relayer/ics24.go b/relayer/ics24.go index aceae4cf8..5b20af079 100644 --- a/relayer/ics24.go +++ b/relayer/ics24.go @@ -8,32 +8,32 @@ import ( ) // Vclient validates the client identifier in the path -func (p *PathEnd) Vclient() error { - return host.ClientIdentifierValidator(p.ClientID) +func (pe *PathEnd) Vclient() error { + return host.ClientIdentifierValidator(pe.ClientID) } // Vconn validates the connection identifier in the path -func (p *PathEnd) Vconn() error { - return host.ConnectionIdentifierValidator(p.ConnectionID) +func (pe *PathEnd) Vconn() error { + return host.ConnectionIdentifierValidator(pe.ConnectionID) } // Vchan validates the channel identifier in the path -func (p *PathEnd) Vchan() error { - return host.ChannelIdentifierValidator(p.ChannelID) +func (pe *PathEnd) Vchan() error { + return host.ChannelIdentifierValidator(pe.ChannelID) } // Vport validates the port identifier in the path -func (p *PathEnd) Vport() error { - return host.PortIdentifierValidator(p.PortID) +func (pe *PathEnd) Vport() error { + return host.PortIdentifierValidator(pe.PortID) } -func (p PathEnd) String() string { - return fmt.Sprintf("%s:cl(%s):co(%s):ch(%s):pt(%s)", p.ChainID, p.ClientID, p.ConnectionID, p.ChannelID, p.PortID) +func (pe PathEnd) String() string { + return fmt.Sprintf("%s:cl(%s):co(%s):ch(%s):pt(%s)", pe.ChainID, pe.ClientID, pe.ConnectionID, pe.ChannelID, pe.PortID) } // PathSet check if the chain has a path set -func (src *Chain) PathSet() bool { - return src.PathEnd != nil +func (c *Chain) PathSet() bool { + return c.PathEnd != nil } // PathsSet checks if the chains have their paths set @@ -47,48 +47,48 @@ func PathsSet(chains ...*Chain) bool { } // SetPath sets the path and validates the identifiers -func (src *Chain) SetPath(p *PathEnd) error { +func (c *Chain) SetPath(p *PathEnd) error { err := p.Validate() if err != nil { - return src.ErrCantSetPath(err) + return c.ErrCantSetPath(err) } - src.PathEnd = p + c.PathEnd = p return nil } // AddPath takes the elements of a path and validates then, setting that path to the chain -func (src *Chain) AddPath(clientID, connectionID, channelID, port, order string) error { - return src.SetPath(&PathEnd{ChainID: src.ChainID, ClientID: clientID, +func (c *Chain) AddPath(clientID, connectionID, channelID, port, order string) error { + return c.SetPath(&PathEnd{ChainID: c.ChainID, ClientID: clientID, ConnectionID: connectionID, ChannelID: channelID, PortID: port, Order: order}) } // Validate returns errors about invalid identifiers as well as // unset path variables for the appropriate type -func (p *PathEnd) Validate() error { - if err := p.Vclient(); err != nil { +func (pe *PathEnd) Validate() error { + if err := pe.Vclient(); err != nil { return err } - if err := p.Vconn(); err != nil { + if err := pe.Vconn(); err != nil { return err } - if err := p.Vchan(); err != nil { + if err := pe.Vchan(); err != nil { return err } - if err := p.Vport(); err != nil { + if err := pe.Vport(); err != nil { return err } - if !(strings.ToUpper(p.Order) == "ORDERED" || strings.ToUpper(p.Order) == "UNORDERED") { - return fmt.Errorf("channel must be either 'ORDERED' or 'UNORDERED' is '%s'", p.Order) + if !(strings.ToUpper(pe.Order) == "ORDERED" || strings.ToUpper(pe.Order) == "UNORDERED") { + return fmt.Errorf("channel must be either 'ORDERED' or 'UNORDERED' is '%s'", pe.Order) } return nil } // ErrPathNotSet returns information what identifiers are needed to relay -func (src *Chain) ErrPathNotSet() error { - return fmt.Errorf("path on chain %s not set", src.ChainID) +func (c *Chain) ErrPathNotSet() error { + return fmt.Errorf("path on chain %s not set", c.ChainID) } // ErrCantSetPath returns an error if the path doesn't set properly -func (src *Chain) ErrCantSetPath(err error) error { - return fmt.Errorf("path on chain %s failed to set: %w", src.ChainID, err) +func (c *Chain) ErrCantSetPath(err error) error { + return fmt.Errorf("path on chain %s failed to set: %w", c.ChainID, err) } diff --git a/relayer/packet-tx.go b/relayer/packet-tx.go index 7fe4c61f0..ffd8976a2 100644 --- a/relayer/packet-tx.go +++ b/relayer/packet-tx.go @@ -28,12 +28,12 @@ func defaultPacketTimeoutStamp() uint64 { } // SendTransferBothSides sends a ICS20 packet from src to dst -func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, +func (c *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, dstAddr fmt.Stringer, source bool) error { if source { amount.Denom = fmt.Sprintf("%s/%s/%s", dst.PathEnd.PortID, dst.PathEnd.ChannelID, amount.Denom) } else { - amount.Denom = fmt.Sprintf("%s/%s/%s", src.PathEnd.PortID, src.PathEnd.ChannelID, amount.Denom) + amount.Denom = fmt.Sprintf("%s/%s/%s", c.PathEnd.PortID, c.PathEnd.ChannelID, amount.Denom) } dstHeader, err := dst.UpdateLiteWithHeader() @@ -50,13 +50,13 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, // MsgTransfer will call SendPacket on src chain txs := RelayMsgs{ - Src: []sdk.Msg{src.PathEnd.MsgTransfer( - dst.PathEnd, dstHeader.GetHeight(), sdk.NewCoins(amount), dstAddrString, src.MustGetAddress(), + Src: []sdk.Msg{c.PathEnd.MsgTransfer( + dst.PathEnd, dstHeader.GetHeight(), sdk.NewCoins(amount), dstAddrString, c.MustGetAddress(), )}, Dst: []sdk.Msg{}, } - if txs.Send(src, dst); !txs.Success() { + if txs.Send(c, dst); !txs.Success() { return fmt.Errorf("failed to send first transaction") } @@ -71,7 +71,7 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, ) if err = retry.Do(func() error { - hs, err = UpdatesWithHeaders(src, dst) + hs, err = UpdatesWithHeaders(c, dst) if err != nil { return err } @@ -81,12 +81,12 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, return err } - seqSend, err = src.QueryNextSeqSend(hs[src.ChainID].Height) + seqSend, err = c.QueryNextSeqSend(hs[c.ChainID].Height) if err != nil { return err } - srcCommitRes, err = src.QueryPacketCommitment(hs[src.ChainID].Height-1, int64(seqSend-1)) + srcCommitRes, err = c.QueryPacketCommitment(hs[c.ChainID].Height-1, int64(seqSend-1)) if err != nil { return err } @@ -101,8 +101,8 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, } // Properly render the source and destination address strings - done = src.UseSDKContext() - srcAddrString := src.MustGetAddress().String() + done = c.UseSDKContext() + srcAddrString := c.MustGetAddress().String() done() done = dst.UseSDKContext() @@ -110,7 +110,7 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, done() // reconstructing packet data here instead of retrieving from an indexed node - xferPacket := src.PathEnd.XferPacket( + xferPacket := c.PathEnd.XferPacket( sdk.NewCoins(amount), srcAddrString, dstAddrString, @@ -121,9 +121,9 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, // information from an indexing node txs = RelayMsgs{ Dst: []sdk.Msg{ - dst.PathEnd.UpdateClient(hs[src.ChainID], dst.MustGetAddress()), + dst.PathEnd.UpdateClient(hs[c.ChainID], dst.MustGetAddress()), dst.PathEnd.MsgRecvPacket( - src.PathEnd, + c.PathEnd, seqRecv.NextSequenceRecv, timeoutHeight, defaultPacketTimeoutStamp(), @@ -136,16 +136,16 @@ func (src *Chain) SendTransferBothSides(dst *Chain, amount sdk.Coin, Src: []sdk.Msg{}, } - txs.Send(src, dst) + txs.Send(c, dst) return nil } // SendTransferMsg initiates an ibs20 transfer from src to dst with the specified args -func (src *Chain) SendTransferMsg(dst *Chain, amount sdk.Coin, dstAddr fmt.Stringer, source bool) error { +func (c *Chain) SendTransferMsg(dst *Chain, amount sdk.Coin, dstAddr fmt.Stringer, source bool) error { if source { amount.Denom = fmt.Sprintf("%s/%s/%s", dst.PathEnd.PortID, dst.PathEnd.ChannelID, amount.Denom) } else { - amount.Denom = fmt.Sprintf("%s/%s/%s", src.PathEnd.PortID, src.PathEnd.ChannelID, amount.Denom) + amount.Denom = fmt.Sprintf("%s/%s/%s", c.PathEnd.PortID, c.PathEnd.ChannelID, amount.Denom) } dstHeader, err := dst.UpdateLiteWithHeader() @@ -160,20 +160,20 @@ func (src *Chain) SendTransferMsg(dst *Chain, amount sdk.Coin, dstAddr fmt.Strin // MsgTransfer will call SendPacket on src chain txs := RelayMsgs{ - Src: []sdk.Msg{src.PathEnd.MsgTransfer( - dst.PathEnd, dstHeader.GetHeight(), sdk.NewCoins(amount), dstAddrString, src.MustGetAddress(), + Src: []sdk.Msg{c.PathEnd.MsgTransfer( + dst.PathEnd, dstHeader.GetHeight(), sdk.NewCoins(amount), dstAddrString, c.MustGetAddress(), )}, Dst: []sdk.Msg{}, } - if txs.Send(src, dst); !txs.success { + if txs.Send(c, dst); !txs.success { return fmt.Errorf("failed to send transfer message") } return nil } // SendPacket sends arbitrary bytes from src to dst -func (src *Chain) SendPacket(dst *Chain, packetData []byte) error { +func (c *Chain) SendPacket(dst *Chain, packetData []byte) error { dstHeader, err := dst.UpdateLiteWithHeader() if err != nil { return err @@ -181,17 +181,17 @@ func (src *Chain) SendPacket(dst *Chain, packetData []byte) error { // MsgSendPacket will call SendPacket on src chain txs := RelayMsgs{ - Src: []sdk.Msg{src.PathEnd.MsgSendPacket( + Src: []sdk.Msg{c.PathEnd.MsgSendPacket( dst.PathEnd, packetData, dstHeader.GetHeight()+uint64(defaultPacketTimeout), defaultPacketTimeoutStamp(), - src.MustGetAddress(), + c.MustGetAddress(), )}, Dst: []sdk.Msg{}, } - if txs.Send(src, dst); !txs.success { + if txs.Send(c, dst); !txs.success { return fmt.Errorf("failed to send packet") } return nil diff --git a/relayer/pathEnd.go b/relayer/pathEnd.go index 0eda03186..a86ff72ba 100644 --- a/relayer/pathEnd.go +++ b/relayer/pathEnd.go @@ -40,28 +40,28 @@ func OrderFromString(order string) ibctypes.Order { } } -func (src *PathEnd) getOrder() ibctypes.Order { - return OrderFromString(strings.ToUpper(src.Order)) +func (pe *PathEnd) getOrder() ibctypes.Order { + return OrderFromString(strings.ToUpper(pe.Order)) } // UpdateClient creates an sdk.Msg to update the client on src with data pulled from dst -func (src *PathEnd) UpdateClient(dstHeader *tmclient.Header, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) UpdateClient(dstHeader *tmclient.Header, signer sdk.AccAddress) sdk.Msg { return tmclient.NewMsgUpdateClient( - src.ClientID, + pe.ClientID, *dstHeader, signer, ) } // CreateClient creates an sdk.Msg to update the client on src with consensus state from dst -func (src *PathEnd) CreateClient(dstHeader *tmclient.Header, trustingPeriod time.Duration, +func (pe *PathEnd) CreateClient(dstHeader *tmclient.Header, trustingPeriod time.Duration, signer sdk.AccAddress) sdk.Msg { if err := dstHeader.ValidateBasic(dstHeader.ChainID); err != nil { panic(err) } // TODO: figure out how to dynmaically set unbonding time return tmclient.NewMsgCreateClient( - src.ClientID, + pe.ClientID, *dstHeader, trustingPeriod, defaultUnbondingTime, @@ -71,10 +71,10 @@ func (src *PathEnd) CreateClient(dstHeader *tmclient.Header, trustingPeriod time } // ConnInit creates a MsgConnectionOpenInit -func (src *PathEnd) ConnInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ConnInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenInit( - src.ConnectionID, - src.ClientID, + pe.ConnectionID, + pe.ClientID, dst.ConnectionID, dst.ClientID, defaultChainPrefix, @@ -84,11 +84,11 @@ func (src *PathEnd) ConnInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { // ConnTry creates a MsgConnectionOpenTry // NOTE: ADD NOTE ABOUT PROOF HEIGHT CHANGE HERE -func (src *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionResponse, +func (pe *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenTry( - src.ConnectionID, - src.ClientID, + pe.ConnectionID, + pe.ClientID, dst.ConnectionID, dst.ClientID, defaultChainPrefix, @@ -103,10 +103,10 @@ func (src *PathEnd) ConnTry(dst *PathEnd, dstConnState connTypes.ConnectionRespo // ConnAck creates a MsgConnectionOpenAck // NOTE: ADD NOTE ABOUT PROOF HEIGHT CHANGE HERE -func (src *PathEnd) ConnAck(dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, +func (pe *PathEnd) ConnAck(dstConnState connTypes.ConnectionResponse, dstConsState clientTypes.ConsensusStateResponse, dstCsHeight int64, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenAck( - src.ConnectionID, + pe.ConnectionID, dstConnState.Proof, dstConsState.Proof, dstConnState.ProofHeight+1, @@ -118,9 +118,9 @@ func (src *PathEnd) ConnAck(dstConnState connTypes.ConnectionResponse, dstConsSt // ConnConfirm creates a MsgConnectionOpenAck // NOTE: ADD NOTE ABOUT PROOF HEIGHT CHANGE HERE -func (src *PathEnd) ConnConfirm(dstConnState connTypes.ConnectionResponse, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ConnConfirm(dstConnState connTypes.ConnectionResponse, signer sdk.AccAddress) sdk.Msg { return connTypes.NewMsgConnectionOpenConfirm( - src.ConnectionID, + pe.ConnectionID, dstConnState.Proof, dstConnState.ProofHeight+1, signer, @@ -128,13 +128,13 @@ func (src *PathEnd) ConnConfirm(dstConnState connTypes.ConnectionResponse, signe } // ChanInit creates a MsgChannelOpenInit -func (src *PathEnd) ChanInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelOpenInit( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, defaultTransferVersion, - src.getOrder(), - []string{src.ConnectionID}, + pe.getOrder(), + []string{pe.ConnectionID}, dst.PortID, dst.ChannelID, signer, @@ -142,13 +142,13 @@ func (src *PathEnd) ChanInit(dst *PathEnd, signer sdk.AccAddress) sdk.Msg { } // ChanTry creates a MsgChannelOpenTry -func (src *PathEnd) ChanTry(dst *PathEnd, dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanTry(dst *PathEnd, dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelOpenTry( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, defaultTransferVersion, dstChanState.Channel.Ordering, - []string{src.ConnectionID}, + []string{pe.ConnectionID}, dst.PortID, dst.ChannelID, dstChanState.Channel.Version, @@ -159,10 +159,10 @@ func (src *PathEnd) ChanTry(dst *PathEnd, dstChanState chanTypes.ChannelResponse } // ChanAck creates a MsgChannelOpenAck -func (src *PathEnd) ChanAck(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanAck(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelOpenAck( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, dstChanState.Channel.Version, dstChanState.Proof, dstChanState.ProofHeight+1, @@ -171,10 +171,10 @@ func (src *PathEnd) ChanAck(dstChanState chanTypes.ChannelResponse, signer sdk.A } // ChanConfirm creates a MsgChannelOpenConfirm -func (src *PathEnd) ChanConfirm(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanConfirm(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelOpenConfirm( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, dstChanState.Proof, dstChanState.ProofHeight+1, signer, @@ -182,19 +182,19 @@ func (src *PathEnd) ChanConfirm(dstChanState chanTypes.ChannelResponse, signer s } // ChanCloseInit creates a MsgChannelCloseInit -func (src *PathEnd) ChanCloseInit(signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanCloseInit(signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelCloseInit( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, signer, ) } // ChanCloseConfirm creates a MsgChannelCloseConfirm -func (src *PathEnd) ChanCloseConfirm(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { +func (pe *PathEnd) ChanCloseConfirm(dstChanState chanTypes.ChannelResponse, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgChannelCloseConfirm( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, dstChanState.Proof, dstChanState.ProofHeight+1, signer, @@ -202,11 +202,11 @@ func (src *PathEnd) ChanCloseConfirm(dstChanState chanTypes.ChannelResponse, sig } // MsgRecvPacket creates a MsgPacket -func (src *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, +func (pe *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, packetData []byte, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgPacket( dst.NewPacket( - src, + pe, sequence, packetData, timeoutHeight, @@ -219,10 +219,10 @@ func (src *PathEnd) MsgRecvPacket(dst *PathEnd, sequence, timeoutHeight, timeout } // MsgTimeout creates MsgTimeout -func (src *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, timeoutStamp uint64, +func (pe *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, timeoutStamp uint64, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgTimeout( - src.NewPacket( + pe.NewPacket( dst, seq, packetData, @@ -237,10 +237,10 @@ func (src *PathEnd) MsgTimeout(dst *PathEnd, packetData []byte, seq, timeout, ti } // MsgAck creates MsgAck -func (src *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, ack, packetData []byte, +func (pe *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp uint64, ack, packetData []byte, proof commitmenttypes.MerkleProof, proofHeight uint64, signer sdk.AccAddress) sdk.Msg { return chanTypes.NewMsgAcknowledgement( - src.NewPacket( + pe.NewPacket( dst, sequence, packetData, @@ -255,11 +255,11 @@ func (src *PathEnd) MsgAck(dst *PathEnd, sequence, timeoutHeight, timeoutStamp u } // MsgTransfer creates a new transfer message -func (src *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins, dstAddr string, +func (pe *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins, dstAddr string, signer sdk.AccAddress) sdk.Msg { return xferTypes.NewMsgTransfer( - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, dstHeight, amount, signer, @@ -268,23 +268,23 @@ func (src *PathEnd) MsgTransfer(dst *PathEnd, dstHeight uint64, amount sdk.Coins } // MsgSendPacket creates a new arbitrary packet message -func (src *PathEnd) MsgSendPacket(dst *PathEnd, packetData []byte, relativeTimeout, timeoutStamp uint64, +func (pe *PathEnd) MsgSendPacket(dst *PathEnd, packetData []byte, relativeTimeout, timeoutStamp uint64, signer sdk.AccAddress) sdk.Msg { // NOTE: Use this just to pass the packet integrity checks. fakeSequence := uint64(1) - packet := chanTypes.NewPacket(packetData, fakeSequence, src.PortID, src.ChannelID, dst.PortID, + packet := chanTypes.NewPacket(packetData, fakeSequence, pe.PortID, pe.ChannelID, dst.PortID, dst.ChannelID, relativeTimeout, timeoutStamp) return NewMsgSendPacket(packet, signer) } // NewPacket returns a new packet from src to dist w -func (src *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, +func (pe *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, timeoutHeight, timeoutStamp uint64) chanTypes.Packet { return chanTypes.NewPacket( packetData, sequence, - src.PortID, - src.ChannelID, + pe.PortID, + pe.ChannelID, dst.PortID, dst.ChannelID, timeoutHeight, @@ -293,7 +293,7 @@ func (src *PathEnd) NewPacket(dst *PathEnd, sequence uint64, packetData []byte, } // XferPacket creates a new transfer packet -func (src *PathEnd) XferPacket(amount sdk.Coins, sender, receiver string) []byte { +func (pe *PathEnd) XferPacket(amount sdk.Coins, sender, receiver string) []byte { return xferTypes.NewFungibleTokenPacketData( amount, sender, @@ -302,9 +302,9 @@ func (src *PathEnd) XferPacket(amount sdk.Coins, sender, receiver string) []byte } // PacketMsg returns a new MsgPacket for forwarding packets from one chain to another -func (src *Chain) PacketMsg(dst *Chain, xferPacket []byte, timeout, timeoutStamp uint64, +func (c *Chain) PacketMsg(dst *Chain, xferPacket []byte, timeout, timeoutStamp uint64, seq int64, dstCommitRes CommitmentResponse) sdk.Msg { - return src.PathEnd.MsgRecvPacket( + return c.PathEnd.MsgRecvPacket( dst.PathEnd, uint64(seq), timeout, @@ -312,6 +312,6 @@ func (src *Chain) PacketMsg(dst *Chain, xferPacket []byte, timeout, timeoutStamp xferPacket, dstCommitRes.Proof, dstCommitRes.ProofHeight, - src.MustGetAddress(), + c.MustGetAddress(), ) } From b73f955e20aee0bac56b0677b1e09cf3f955a855 Mon Sep 17 00:00:00 2001 From: Marko Baricevic Date: Tue, 26 May 2020 17:30:22 +0200 Subject: [PATCH 05/17] make unordered a const --- cmd/config.go | 5 ++++- cmd/paths.go | 8 ++++---- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/cmd/config.go b/cmd/config.go index 5c90a21bb..d40f56615 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -31,7 +31,10 @@ import ( "gopkg.in/yaml.v2" ) -const ORDERED = "ORDERED" +const ( + ORDERED = "ORDERED" + UNORDERED = "UNORDERED" +) func configCmd() *cobra.Command { cmd := &cobra.Command{ diff --git a/cmd/paths.go b/cmd/paths.go index caf7f77a3..fc6ff24f6 100644 --- a/cmd/paths.go +++ b/cmd/paths.go @@ -89,11 +89,11 @@ func pathsGenCmd() *cobra.Command { } if unordered { - path.Src.Order = "UNORDERED" - path.Dst.Order = "UNORDERED" + path.Src.Order = UNORDERED + path.Dst.Order = UNORDERED } else { - path.Src.Order = "ORDERED" - path.Dst.Order = "ORDERED" + path.Src.Order = ORDERED + path.Dst.Order = ORDERED } force, err := cmd.Flags().GetBool(flagForce) From 9ab15cce51887e529c7c65287d9805706f2e4d59 Mon Sep 17 00:00:00 2001 From: colin axner <25233464+colin-axner@users.noreply.github.com> Date: Tue, 14 Jul 2020 12:35:36 +0200 Subject: [PATCH 06/17] Update faucet.go --- relayer/faucet.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relayer/faucet.go b/relayer/faucet.go index d2e91f113..6f0b81e33 100644 --- a/relayer/faucet.go +++ b/relayer/faucet.go @@ -96,7 +96,7 @@ func (c *Chain) FaucetHandler(fromKey sdk.AccAddress, amounts sdk.Coins) func(w } } -func (c *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amount sdk.Coin) error { +func (c *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amounts sdk.Coin) error { // Set sdk config to use custom Bech32 account prefix info, err := c.Keybase.KeyByAddress(fromAddr) From ef7425f28c7ec70a638cffe359cc9fd4186d8093 Mon Sep 17 00:00:00 2001 From: colin axner <25233464+colin-axner@users.noreply.github.com> Date: Tue, 14 Jul 2020 12:39:32 +0200 Subject: [PATCH 07/17] fix merge errors --- relayer/faucet.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relayer/faucet.go b/relayer/faucet.go index 6f0b81e33..f0aa2cd35 100644 --- a/relayer/faucet.go +++ b/relayer/faucet.go @@ -96,7 +96,7 @@ func (c *Chain) FaucetHandler(fromKey sdk.AccAddress, amounts sdk.Coins) func(w } } -func (c *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amounts sdk.Coin) error { +func (c *Chain) faucetSend(fromAddr, toAddr sdk.AccAddress, amounts sdk.Coins) error { // Set sdk config to use custom Bech32 account prefix info, err := c.Keybase.KeyByAddress(fromAddr) From e8ec2e43e9b5e3e8483a579030025dc4008fbbc2 Mon Sep 17 00:00:00 2001 From: Marko Date: Tue, 14 Jul 2020 12:39:56 +0200 Subject: [PATCH 08/17] Update test/test_setup.go Co-authored-by: colin axner <25233464+colin-axner@users.noreply.github.com> --- test/test_setup.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test_setup.go b/test/test_setup.go index d0debced6..8a86e2151 100644 --- a/test/test_setup.go +++ b/test/test_setup.go @@ -183,7 +183,7 @@ func cleanUpTest(t *testing.T, testsDone <-chan struct{}, contDone chan<- struct // remove all the docker containers for i, r := range resources { if err := pool.Purge(r); err != nil { - require.NoError(t, fmt.Errorf("cculd not purge container %s: %w", r.Container.Name, err)) + require.NoError(t, fmt.Errorf("could not purge container %s: %w", r.Container.Name, err)) } c := getLoggingChain(chains, r) chains[i].Log(fmt.Sprintf("- [%s] SPUN DOWN CONTAINER %s from %s", c.ChainID, r.Container.Name, From f2fb27c01f8cf16f249edb24bc68f520c486b2ff Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 12:50:50 +0200 Subject: [PATCH 09/17] fix lint --- relayer/packet-tx.go | 1 - 1 file changed, 1 deletion(-) diff --git a/relayer/packet-tx.go b/relayer/packet-tx.go index ffd8976a2..0bd43fd8c 100644 --- a/relayer/packet-tx.go +++ b/relayer/packet-tx.go @@ -15,7 +15,6 @@ var ( defaultChainPrefix = commitmentypes.NewMerklePrefix([]byte("ibc")) defaultIBCVersion = "1.0.0" defaultIBCVersions = []string{defaultIBCVersion} - defaultTransferVersion = "ics20-1" defaultUnbondingTime = time.Hour * 504 // 3 weeks in hours defaultMaxClockDrift = time.Second * 10 defaultPacketTimeout = 1000 From 6f1c034bfc36ab1f5f32077519b231515f2612af Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 12:56:35 +0200 Subject: [PATCH 10/17] more linting fixes --- Makefile | 2 +- cmd/config.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Makefile b/Makefile index 631754b2a..32eef71fd 100644 --- a/Makefile +++ b/Makefile @@ -54,7 +54,7 @@ test-agoric: @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestAgoric* test-coco: - @TEST_DEBUG=true go test -mod=mod -v -race ./test/... -run TestCoCo* + @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestCoCo* coverage: @echo "viewing test coverage..." diff --git a/cmd/config.go b/cmd/config.go index 394e5a148..93ad2a3dc 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -32,8 +32,8 @@ import ( ) const ( - ORDERED = "ORDERED" - UNORDERED = "UNORDERED" + ORDERED = "ORDERED" + UNORDERED = "UNORDERED" defaultOrder = ORDERED defaultVersion = "ics20-1" ) From f34896c8f7c5516e7a32b2a4e3e93c026ecd17ae Mon Sep 17 00:00:00 2001 From: colin axner <25233464+colin-axner@users.noreply.github.com> Date: Tue, 14 Jul 2020 14:46:04 +0200 Subject: [PATCH 11/17] Apply suggestions from code review --- relayer/client-tx.go | 4 ++-- relayer/query.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/relayer/client-tx.go b/relayer/client-tx.go index fa81f80aa..70da5e3dd 100644 --- a/relayer/client-tx.go +++ b/relayer/client-tx.go @@ -11,7 +11,7 @@ import ( func (c *Chain) CreateClients(dst *Chain) (err error) { clients := &RelayMsgs{Src: []sdk.Msg{}, Dst: []sdk.Msg{}} - // Create client for dst on c if it doesn't exist + // Create client for the destination chain on the source chain if it doesn't exist var srcCs, dstCs *clientTypes.StateResponse if srcCs, err = c.QueryClientState(); err != nil { return err @@ -26,7 +26,7 @@ func (c *Chain) CreateClients(dst *Chain) (err error) { clients.Src = append(clients.Src, c.PathEnd.CreateClient(dstH, dst.GetTrustingPeriod(), c.MustGetAddress())) } - // Create client for c on dst if it doesn't exist + // Create client for the source chain on destination chain if it doesn't exist if dstCs, err = dst.QueryClientState(); err != nil { return err } else if dstCs == nil { diff --git a/relayer/query.go b/relayer/query.go index 1e4389459..c68b9db54 100644 --- a/relayer/query.go +++ b/relayer/query.go @@ -139,7 +139,7 @@ func (c *Chain) QueryClientConsensusState(srcHeight, return clientTypes.NewConsensusStateResponse("notfound", nil, nil, 0), nil } - var cs clientExported.ConsensusState + var cs clientexported.ConsensusState if err = c.Amino.UnmarshalBinaryLengthPrefixed(res.Value, &cs); err != nil { if err = c.Amino.UnmarshalBinaryBare(res.Value, &cs); err != nil { return conStateRes, qClntConsStateErr(err) @@ -218,7 +218,7 @@ func (c *Chain) QueryClientState() (*clientTypes.StateResponse, error) { return nil, nil } - var cs clientExported.ClientState + var cs clientexported.ClientState // If this decoding fails, try with UnmarshalBinaryLengthPrefixed this changed // reciently and will help support older versions. From 5809f3ad61416353afd686c84c0c6059da1c02ef Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 15:01:52 +0200 Subject: [PATCH 12/17] fix bug --- relayer/relayMsgs.go | 2 +- test/test_setup.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/relayer/relayMsgs.go b/relayer/relayMsgs.go index a21e5e18a..2003de7f1 100644 --- a/relayer/relayMsgs.go +++ b/relayer/relayMsgs.go @@ -47,7 +47,7 @@ func (r *RelayMsgs) IsMaxTx(msgLen, txSize uint64) bool { func (r *RelayMsgs) Send(src, dst *Chain) { var ( msgLen, txSize uint64 - msgs = make([]sdk.Msg, len(r.Src)) + msgs []sdk.Msg ) r.success = true diff --git a/test/test_setup.go b/test/test_setup.go index 8a86e2151..6048dfbfb 100644 --- a/test/test_setup.go +++ b/test/test_setup.go @@ -42,9 +42,9 @@ func spinUpTestChains(t *testing.T, testChains ...testChain) ry.Chains { } // make each container and initialize the chains - for _, tc := range testChains { + for i, tc := range testChains { c := newTestChain(t, tc) - chains = append(chains, c) + chains[i] = c wg.Add(1) go spinUpTestContainer(t, rchan, pool, c, dir, &wg, tc) } From d27f936ff0a8d4cdf6828236651029b5a08c7066 Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 15:33:50 +0200 Subject: [PATCH 13/17] fix build --- relayer/query.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/relayer/query.go b/relayer/query.go index c68b9db54..966e8bb55 100644 --- a/relayer/query.go +++ b/relayer/query.go @@ -14,7 +14,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" authTypes "github.com/cosmos/cosmos-sdk/x/auth/types" bankTypes "github.com/cosmos/cosmos-sdk/x/bank/types" - clientExported "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" + clientexported "github.com/cosmos/cosmos-sdk/x/ibc/02-client/exported" clientTypes "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" connTypes "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" chanTypes "github.com/cosmos/cosmos-sdk/x/ibc/04-channel/types" @@ -271,11 +271,11 @@ func QueryClientStatePair(src, dst *Chain) (map[string]*clientTypes.StateRespons func qClntStateErr(err error) error { return fmt.Errorf("query client state failed: %w", err) } // QueryClients queries all the clients! -func (c *Chain) QueryClients(page, limit int) ([]clientExported.ClientState, error) { +func (c *Chain) QueryClients(page, limit int) ([]clientexported.ClientState, error) { var ( bz []byte err error - clients []clientExported.ClientState + clients []clientexported.ClientState ) if bz, err = c.Cdc.MarshalJSON(clientTypes.NewQueryAllClientsParams(page, limit)); err != nil { From a89bd0c7789a3fe5d6333d57502f8dd3260cb771 Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 15:45:16 +0200 Subject: [PATCH 14/17] fix bug and remove race condition check --- Makefile | 12 ++++++------ relayer/query.go | 4 ++-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index 32eef71fd..5a8119ff9 100644 --- a/Makefile +++ b/Makefile @@ -39,22 +39,22 @@ install: go.sum # Tests / CI ############################################################################### test: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... + @TEST_DEBUG=true go test -mod=readonly -v ./test/... test-gaia: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestGaia* + @TEST_DEBUG=true go test -mod=readonly -v ./test/... -run TestGaia* test-mtd: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestMtd* + @TEST_DEBUG=true go test -mod=readonly -v ./test/... -run TestMtd* test-rocketzone: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestRocket* + @TEST_DEBUG=true go test -mod=readonly -v ./test/... -run TestRocket* test-agoric: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestAgoric* + @TEST_DEBUG=true go test -mod=readonly -v ./test/... -run TestAgoric* test-coco: - @TEST_DEBUG=true go test -mod=readonly -v -race ./test/... -run TestCoCo* + @TEST_DEBUG=true go test -mod=readonly -v ./test/... -run TestCoCo* coverage: @echo "viewing test coverage..." diff --git a/relayer/query.go b/relayer/query.go index 966e8bb55..d4f8b6f99 100644 --- a/relayer/query.go +++ b/relayer/query.go @@ -1238,7 +1238,7 @@ func ParseEvents(e string) ([]string, error) { var tmEvents = make([]string, len(events)) - for _, event := range events { + for i, event := range events { if !strings.Contains(event, "=") { return []string{}, fmt.Errorf("invalid event; event %s should be of the format: %s", event, eventFormat) } else if strings.Count(event, "=") > 1 { @@ -1252,7 +1252,7 @@ func ParseEvents(e string) ([]string, error) { event = fmt.Sprintf("%s='%s'", tokens[0], tokens[1]) } - tmEvents = append(tmEvents, event) + tmEvents[i] = event } return tmEvents, nil } From c75bf96fd84bce96ce0cc7b4630d8976f98b8a32 Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 15:51:53 +0200 Subject: [PATCH 15/17] fix lint --- relayer/relayMsgs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relayer/relayMsgs.go b/relayer/relayMsgs.go index 2003de7f1..3d5829bd0 100644 --- a/relayer/relayMsgs.go +++ b/relayer/relayMsgs.go @@ -47,7 +47,7 @@ func (r *RelayMsgs) IsMaxTx(msgLen, txSize uint64) bool { func (r *RelayMsgs) Send(src, dst *Chain) { var ( msgLen, txSize uint64 - msgs []sdk.Msg + msgs []sdk.Msg //nolint:prealloc ) r.success = true From a281865ce562545732dce66fab4920e3791d4adb Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 16:43:24 +0200 Subject: [PATCH 16/17] fix lint --- relayer/relayMsgs.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/relayer/relayMsgs.go b/relayer/relayMsgs.go index 3d5829bd0..38c423322 100644 --- a/relayer/relayMsgs.go +++ b/relayer/relayMsgs.go @@ -47,7 +47,7 @@ func (r *RelayMsgs) IsMaxTx(msgLen, txSize uint64) bool { func (r *RelayMsgs) Send(src, dst *Chain) { var ( msgLen, txSize uint64 - msgs []sdk.Msg //nolint:prealloc + msgs []sdk.Msg //nolint:prealloc // can not be pre allocated ) r.success = true From 9662cc09a8ddd9e6f1e4464b7d18a9ce1939a5cc Mon Sep 17 00:00:00 2001 From: Colin Axner Date: Tue, 14 Jul 2020 16:47:09 +0200 Subject: [PATCH 17/17] try to fix lint --- relayer/relayMsgs.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/relayer/relayMsgs.go b/relayer/relayMsgs.go index 38c423322..d1f7f2aaa 100644 --- a/relayer/relayMsgs.go +++ b/relayer/relayMsgs.go @@ -45,9 +45,10 @@ func (r *RelayMsgs) IsMaxTx(msgLen, txSize uint64) bool { // Send sends the messages with appropriate output // TODO: Parallelize? Maybe? func (r *RelayMsgs) Send(src, dst *Chain) { + //nolint:prealloc // can not be pre allocated var ( msgLen, txSize uint64 - msgs []sdk.Msg //nolint:prealloc // can not be pre allocated + msgs []sdk.Msg ) r.success = true