-
Notifications
You must be signed in to change notification settings - Fork 2
/
p2p.go
91 lines (75 loc) · 1.92 KB
/
p2p.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
package p2p
import (
"fmt"
"strconv"
logging "github.com/ipfs/go-log"
p2phost "github.com/libp2p/go-libp2p-core/host"
peer "github.com/libp2p/go-libp2p-core/peer"
pstore "github.com/libp2p/go-libp2p-core/peerstore"
ma "github.com/multiformats/go-multiaddr"
)
var log = logging.Logger("p2p-mount")
// P2P structure holds information on currently running streams/Listeners
type P2P struct {
ListenersLocal *Listeners
ListenersP2P *Listeners
Streams *StreamRegistry
identity peer.ID
peerHost p2phost.Host
peerstore pstore.Peerstore
}
// New creates new P2P struct
func New(identity peer.ID, peerHost p2phost.Host, peerstore pstore.Peerstore) *P2P {
return &P2P{
identity: identity,
peerHost: peerHost,
peerstore: peerstore,
ListenersLocal: newListenersLocal(),
ListenersP2P: newListenersP2P(peerHost),
Streams: &StreamRegistry{
Streams: map[uint64]*Stream{},
ConnManager: peerHost.ConnManager(),
conns: map[peer.ID]int{},
},
}
}
// CheckProtoExists checks whether a proto handler is registered to
// mux handler
func (p2p *P2P) CheckProtoExists(proto string) bool {
protos := p2p.peerHost.Mux().Protocols()
for _, p := range protos {
if p != proto {
continue
}
return true
}
return false
}
// checkPort checks whether target multiaddr contains tcp or udp protocol
// and whether the port is equal to 0
func CheckPort(target ma.Multiaddr) error {
// get tcp or udp port from multiaddr
getPort := func() (string, error) {
sport, _ := target.ValueForProtocol(ma.P_TCP)
if sport != "" {
return sport, nil
}
sport, _ = target.ValueForProtocol(ma.P_UDP)
if sport != "" {
return sport, nil
}
return "", fmt.Errorf("address does not contain tcp or udp protocol")
}
sport, err := getPort()
if err != nil {
return err
}
port, err := strconv.Atoi(sport)
if err != nil {
return err
}
if port == 0 {
return fmt.Errorf("port can not be 0")
}
return nil
}