forked from ckousik/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pbconv.go
96 lines (74 loc) · 1.87 KB
/
pbconv.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package util
import (
"errors"
"github.com/John-LittleBearLabs/go-libp2p/core/peer"
pbv1 "github.com/John-LittleBearLabs/go-libp2p/p2p/protocol/circuitv1/pb"
pbv2 "github.com/John-LittleBearLabs/go-libp2p/p2p/protocol/circuitv2/pb"
ma "github.com/multiformats/go-multiaddr"
)
func PeerToPeerInfoV1(p *pbv1.CircuitRelay_Peer) (peer.AddrInfo, error) {
if p == nil {
return peer.AddrInfo{}, errors.New("nil peer")
}
id, err := peer.IDFromBytes(p.Id)
if err != nil {
return peer.AddrInfo{}, err
}
var addrs []ma.Multiaddr
if len(p.Addrs) > 0 {
addrs = make([]ma.Multiaddr, 0, len(p.Addrs))
}
for _, addrBytes := range p.Addrs {
a, err := ma.NewMultiaddrBytes(addrBytes)
if err == nil {
addrs = append(addrs, a)
}
}
return peer.AddrInfo{ID: id, Addrs: addrs}, nil
}
func PeerInfoToPeerV1(pi peer.AddrInfo) *pbv1.CircuitRelay_Peer {
var addrs [][]byte
if len(pi.Addrs) > 0 {
addrs = make([][]byte, 0, len(pi.Addrs))
}
for _, addr := range pi.Addrs {
addrs = append(addrs, addr.Bytes())
}
p := new(pbv1.CircuitRelay_Peer)
p.Id = []byte(pi.ID)
p.Addrs = addrs
return p
}
func PeerToPeerInfoV2(p *pbv2.Peer) (peer.AddrInfo, error) {
if p == nil {
return peer.AddrInfo{}, errors.New("nil peer")
}
id, err := peer.IDFromBytes(p.Id)
if err != nil {
return peer.AddrInfo{}, err
}
var addrs []ma.Multiaddr
if len(p.Addrs) > 0 {
addrs = make([]ma.Multiaddr, 0, len(p.Addrs))
}
for _, addrBytes := range p.Addrs {
a, err := ma.NewMultiaddrBytes(addrBytes)
if err == nil {
addrs = append(addrs, a)
}
}
return peer.AddrInfo{ID: id, Addrs: addrs}, nil
}
func PeerInfoToPeerV2(pi peer.AddrInfo) *pbv2.Peer {
var addrs [][]byte
if len(pi.Addrs) > 0 {
addrs = make([][]byte, 0, len(pi.Addrs))
}
for _, addr := range pi.Addrs {
addrs = append(addrs, addr.Bytes())
}
p := new(pbv2.Peer)
p.Id = []byte(pi.ID)
p.Addrs = addrs
return p
}