github.com/aergoio/aergo@v1.3.1/types/p2ptypes.go (about) 1 /* 2 * @file 3 * @copyright defined in aergo/LICENSE.txt 4 */ 5 6 package types 7 8 import ( 9 "fmt" 10 "github.com/aergoio/aergo/internal/network" 11 core "github.com/libp2p/go-libp2p-core" 12 "github.com/libp2p/go-libp2p-core/crypto" 13 "github.com/libp2p/go-libp2p-core/peer" 14 "github.com/multiformats/go-multiaddr" 15 "github.com/pkg/errors" 16 "net" 17 "strings" 18 ) 19 20 // PeerID is identier of peer. it is alias of libp2p.PeerID for now 21 type PeerID = core.PeerID 22 23 func IDB58Decode(b58 string) (PeerID, error) { 24 return peer.IDB58Decode(b58) 25 } 26 func IDB58Encode(pid PeerID) string { 27 return peer.IDB58Encode(pid) 28 } 29 30 func IDFromBytes(b []byte) (PeerID, error) { 31 return peer.IDFromBytes(b) 32 } 33 func IDFromPublicKey(pubKey crypto.PubKey) (PeerID, error) { 34 return peer.IDFromPublicKey(pubKey) 35 } 36 func IDFromPrivateKey(sk crypto.PrivKey) (PeerID, error) { 37 return peer.IDFromPrivateKey(sk) 38 } 39 40 // Stream is alias of libp2p.Stream 41 type Stream = core.Stream 42 43 // Multiaddr is alias of 44 type Multiaddr = multiaddr.Multiaddr 45 46 var InvalidArgument = errors.New("invalid argument") 47 48 // ToMultiAddr make libp2p compatible Multiaddr object 49 func ToMultiAddr(ipAddr net.IP, port uint32) (multiaddr.Multiaddr, error) { 50 var addrString string 51 if ipAddr.To4() != nil { 52 addrString = fmt.Sprintf("/ip4/%s/tcp/%d", ipAddr.String(), port) 53 } else if ipAddr.To16() != nil { 54 addrString = fmt.Sprintf("/ip6/%s/tcp/%d", ipAddr.String(), port) 55 } else { 56 return nil, InvalidArgument 57 } 58 peerAddr, err := multiaddr.NewMultiaddr(addrString) 59 if err != nil { 60 return nil, err 61 } 62 return peerAddr, nil 63 } 64 65 // ParseMultiaddrWithResolve parse string to multiaddr, additionally accept domain name with protocol /dns 66 // NOTE: this function is temporarily use until go-multiaddr start to support dns. 67 func ParseMultiaddrWithResolve(str string) (multiaddr.Multiaddr, error) { 68 ma, err := multiaddr.NewMultiaddr(str) 69 if err != nil { 70 // multiaddr is not support domain name yet. change domain name to ip address manually 71 split := strings.Split(str, "/") 72 if len(split) < 3 || !strings.HasPrefix(split[1], "dns") { 73 return nil, err 74 } 75 domainName := split[2] 76 ips, err := network.ResolveHostDomain(domainName) 77 if err != nil { 78 return nil, fmt.Errorf("Could not get IPs: %v\n", err) 79 } 80 // use ipv4 as possible. 81 ipSelected := false 82 for _, ip := range ips { 83 if ip.To4() != nil { 84 split[1] = "ip4" 85 split[2] = ip.To4().String() 86 ipSelected = true 87 break 88 } 89 } 90 if !ipSelected { 91 for _, ip := range ips { 92 if ip.To16() != nil { 93 split[1] = "ip6" 94 split[2] = ip.To16().String() 95 ipSelected = true 96 break 97 } 98 } 99 } 100 if !ipSelected { 101 return nil, err 102 } 103 rejoin := strings.Join(split, "/") 104 return multiaddr.NewMultiaddr(rejoin) 105 } 106 return ma, nil 107 }