2019-05-23 01:31:11 +08:00
|
|
|
package peer
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
ma "github.com/multiformats/go-multiaddr"
|
|
|
|
)
|
|
|
|
|
|
|
|
// AddrInfo is a small struct used to pass around a peer with
|
|
|
|
// a set of addresses (and later, keys?).
|
|
|
|
type AddrInfo struct {
|
|
|
|
ID ID
|
|
|
|
Addrs []ma.Multiaddr
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ fmt.Stringer = AddrInfo{}
|
|
|
|
|
|
|
|
func (pi AddrInfo) String() string {
|
|
|
|
return fmt.Sprintf("{%v: %v}", pi.ID, pi.Addrs)
|
|
|
|
}
|
|
|
|
|
|
|
|
var ErrInvalidAddr = fmt.Errorf("invalid p2p multiaddr")
|
|
|
|
|
|
|
|
func AddrInfoFromP2pAddr(m ma.Multiaddr) (*AddrInfo, error) {
|
|
|
|
if m == nil {
|
|
|
|
return nil, ErrInvalidAddr
|
|
|
|
}
|
|
|
|
|
2019-05-31 12:57:09 +08:00
|
|
|
transport, p2ppart := ma.SplitLast(m)
|
|
|
|
if p2ppart == nil || p2ppart.Protocol().Code != ma.P_P2P {
|
2019-05-23 01:31:11 +08:00
|
|
|
return nil, ErrInvalidAddr
|
|
|
|
}
|
2019-05-31 12:57:09 +08:00
|
|
|
id, err := IDFromBytes(p2ppart.RawValue())
|
2019-05-23 01:31:11 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-05-31 12:57:09 +08:00
|
|
|
info := &AddrInfo{ID: id}
|
|
|
|
if transport != nil {
|
|
|
|
info.Addrs = []ma.Multiaddr{transport}
|
2019-05-23 01:31:11 +08:00
|
|
|
}
|
2019-05-31 12:57:09 +08:00
|
|
|
return info, nil
|
2019-05-23 01:31:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func AddrInfoToP2pAddrs(pi *AddrInfo) ([]ma.Multiaddr, error) {
|
|
|
|
var addrs []ma.Multiaddr
|
2019-05-31 12:57:09 +08:00
|
|
|
p2ppart, err := ma.NewComponent("p2p", IDB58Encode(pi.ID))
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2019-05-23 01:31:11 +08:00
|
|
|
for _, addr := range pi.Addrs {
|
2019-05-31 12:57:09 +08:00
|
|
|
addrs = append(addrs, addr.Encapsulate(p2ppart))
|
2019-05-23 01:31:11 +08:00
|
|
|
}
|
|
|
|
return addrs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (pi *AddrInfo) Loggable() map[string]interface{} {
|
|
|
|
return map[string]interface{}{
|
|
|
|
"peerID": pi.ID.Pretty(),
|
|
|
|
"addrs": pi.Addrs,
|
|
|
|
}
|
|
|
|
}
|