Add func to construct /ipfs addrs from PeerInfo

This commit is contained in:
Lars Gierth 2017-04-26 01:44:38 +02:00
parent 17c3462143
commit 6a60f4058e
2 changed files with 52 additions and 0 deletions

View File

@ -50,6 +50,19 @@ func InfoFromP2pAddr(m ma.Multiaddr) (*PeerInfo, error) {
}, nil
}
func InfoToP2pAddrs(pi *PeerInfo) ([]ma.Multiaddr, error) {
addrs := []ma.Multiaddr{}
tpl := "/" + ma.ProtocolWithCode(ma.P_IPFS).Name + "/"
for _, addr := range pi.Addrs {
p2paddr, err := ma.NewMultiaddr(tpl + peer.IDB58Encode(pi.ID))
if err != nil {
return nil, err
}
addrs = append(addrs, addr.Encapsulate(p2paddr))
}
return addrs, nil
}
func (pi *PeerInfo) Loggable() map[string]interface{} {
return map[string]interface{}{
"peerID": pi.ID.Pretty(),

View File

@ -83,3 +83,42 @@ func TestP2pAddrParsing(t *testing.T) {
t.Fatal("didnt get expected address")
}
}
func TestP2pAddrConstruction(t *testing.T) {
id, err := peer.IDB58Decode("QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ")
if err != nil {
t.Error(err)
}
addr := ma.StringCast("/ip4/1.2.3.4/tcp/4536")
p2paddr := ma.Join(addr, ma.StringCast("/ipfs/"+peer.IDB58Encode(id)))
pi := &PeerInfo{ID: id, Addrs: []ma.Multiaddr{addr}}
p2paddrs, err := InfoToP2pAddrs(pi)
if err != nil {
t.Error(err)
}
if len(p2paddrs) != 1 {
t.Fatalf("expected 1 addr, got %d", len(p2paddrs))
}
if !p2paddr.Equal(p2paddrs[0]) {
t.Fatalf("expected [%s], got [%s]", p2paddr, p2paddrs[0])
}
pi = &PeerInfo{ID: id}
p2paddrs, err = InfoToP2pAddrs(pi)
if err != nil {
t.Error(err)
}
if len(p2paddrs) > 0 {
t.Fatalf("expected 0 addrs, got %d", len(p2paddrs))
}
pi = &PeerInfo{Addrs: []ma.Multiaddr{ma.StringCast("/ip4/1.2.3.4/tcp/4536")}}
_, err = InfoToP2pAddrs(pi)
if err == nil {
t.Fatalf("expected error, got none")
}
}