-
Notifications
You must be signed in to change notification settings - Fork 199
/
connectableHost.go
53 lines (43 loc) · 1.29 KB
/
connectableHost.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
package libp2p
import (
"context"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/multiformats/go-multiaddr"
)
// PeerInfoHandler is the signature of the handler that gets called whenever an action for a peerInfo is triggered
type PeerInfoHandler func(pInfo peer.AddrInfo)
// ConnectableHost is an enhanced Host interface that has the ability to connect to a string address
type ConnectableHost interface {
host.Host
ConnectToPeer(ctx context.Context, address string) error
IsInterfaceNil() bool
}
type connectableHost struct {
host.Host
}
// NewConnectableHost creates a new connectable host implementation
func NewConnectableHost(h host.Host) *connectableHost {
return &connectableHost{
Host: h,
}
}
// ConnectToPeer connects to a peer by knowing its string address
func (connHost *connectableHost) ConnectToPeer(ctx context.Context, address string) error {
multiAddr, err := multiaddr.NewMultiaddr(address)
if err != nil {
return err
}
pInfo, err := peer.AddrInfoFromP2pAddr(multiAddr)
if err != nil {
return err
}
return connHost.Connect(ctx, *pInfo)
}
// IsInterfaceNil returns true if there is no value under the interface
func (connHost *connectableHost) IsInterfaceNil() bool {
if connHost == nil {
return true
}
return false
}