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

Commit

Permalink
feat: add ability to parse addr infos from strings (#143)
Browse files Browse the repository at this point in the history
  • Loading branch information
rach-id authored Feb 15, 2023
1 parent 27f6375 commit ac657a0
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
20 changes: 20 additions & 0 deletions cmd/qgb/helpers/parse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package helpers

import (
"github.com/libp2p/go-libp2p/core/peer"
tmlog "github.com/tendermint/tendermint/libs/log"
)

// ParseAddrInfos converts strings to AddrInfos
func ParseAddrInfos(logger tmlog.Logger, addrs []string) ([]peer.AddrInfo, error) {
infos := make([]peer.AddrInfo, 0, len(addrs))
for _, addr := range addrs {
info, err := peer.AddrInfoFromString(addr)
if err != nil {
logger.Error("parsing info from multiaddr", "addr", addr, "err", err)
return nil, err
}
infos = append(infos, *info)
}
return infos, nil
}
65 changes: 65 additions & 0 deletions cmd/qgb/helpers/parse_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package helpers

import (
"testing"

"github.com/libp2p/go-libp2p/core/peer"
"github.com/stretchr/testify/assert"
tmlog "github.com/tendermint/tendermint/libs/log"
)

func TestParseAddrInfos(t *testing.T) {
testCases := []struct {
name string
addrs []string
want []peer.AddrInfo
shouldErr bool
}{
{
name: "empty input",
addrs: []string{},
want: []peer.AddrInfo{},
},
{
name: "valid input",
addrs: []string{
"/ip4/127.0.0.1/tcp/8080/p2p/12D3KooWHr2wqFAsMXnPzpFsgxmePgXb8BqpkePebwUgLyZc95bd",
"/dns4/limani.celestia-devops.dev/tcp/2121/p2p/12D3KooWDgG69kXfmSiHjUErN2ahpUC1SXpSfB2urrqMZ6aWC8NS",
},
want: []peer.AddrInfo{
func() peer.AddrInfo {
info, _ := peer.AddrInfoFromString("/ip4/127.0.0.1/tcp/8080/p2p/12D3KooWHr2wqFAsMXnPzpFsgxmePgXb8BqpkePebwUgLyZc95bd")
return *info
}(),
func() peer.AddrInfo {
info, _ := peer.AddrInfoFromString("/dns4/limani.celestia-devops.dev/tcp/2121/p2p/12D3KooWDgG69kXfmSiHjUErN2ahpUC1SXpSfB2urrqMZ6aWC8NS")
return *info
}(),
},
},
{
name: "invalid multiaddr",
addrs: []string{
"/ip4/127.0.0.1/tcp/8080",
"invalid-multiaddr",
},
shouldErr: true,
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
got, err := ParseAddrInfos(tmlog.NewNopLogger(), tc.addrs)
if tc.shouldErr {
assert.Error(t, err)
assert.Nil(t, got)
} else {
assert.NoError(t, err)
for i, info := range tc.want {
assert.Equal(t, info.ID.String(), got[i].ID.String())
assert.Equal(t, info.Addrs, got[i].Addrs)
}
}
})
}
}

0 comments on commit ac657a0

Please sign in to comment.