-
Notifications
You must be signed in to change notification settings - Fork 376
/
helper.go
55 lines (48 loc) · 1.08 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package ipfsutil
import (
"context"
"errors"
"fmt"
peer "github.com/libp2p/go-libp2p-core/peer"
madns "github.com/multiformats/go-multiaddr-dns"
ma "github.com/multiformats/go-multiaddr"
)
// parseIpfsAddr is a function that takes in addr string and return ipfsAddrs
func ParseAndResolveIpfsAddr(ctx context.Context, addr string) (*peer.AddrInfo, error) {
maddr, err := ma.NewMultiaddr(addr)
if err != nil {
return nil, err
}
if !madns.Matches(maddr) {
return peer.AddrInfoFromP2pAddr(maddr)
}
addrs, err := madns.Resolve(ctx, maddr)
if err != nil {
return nil, err
}
if len(addrs) == 0 {
return nil, errors.New("fail to resolve the multiaddr:" + maddr.String())
}
var info peer.AddrInfo
for _, addr := range addrs {
taddr, id := peer.SplitAddr(addr)
if id == "" {
// not an ipfs addr, skipping.
continue
}
switch info.ID {
case "":
info.ID = id
case id:
default:
return nil, fmt.Errorf(
"ambiguous maddr %s could refer to %s or %s",
maddr,
info.ID,
id,
)
}
info.Addrs = append(info.Addrs, taddr)
}
return &info, nil
}