-
Notifications
You must be signed in to change notification settings - Fork 281
/
clusterhost.go
42 lines (36 loc) · 1.05 KB
/
clusterhost.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
package ipfscluster
import (
"context"
"encoding/hex"
libp2p "github.com/libp2p/go-libp2p"
host "github.com/libp2p/go-libp2p-host"
ipnet "github.com/libp2p/go-libp2p-interface-pnet"
pnet "github.com/libp2p/go-libp2p-pnet"
ma "github.com/multiformats/go-multiaddr"
)
// NewClusterHost creates a libp2p Host with the options from the
// provided cluster configuration.
func NewClusterHost(ctx context.Context, cfg *Config) (host.Host, error) {
var prot ipnet.Protector
var err error
// Create protector if we have a secret.
if cfg.Secret != nil && len(cfg.Secret) > 0 {
var key [32]byte
copy(key[:], cfg.Secret)
prot, err = pnet.NewV1ProtectorFromBytes(&key)
if err != nil {
return nil, err
}
}
return libp2p.New(
ctx,
libp2p.Identity(cfg.PrivateKey),
libp2p.ListenAddrs([]ma.Multiaddr{cfg.ListenAddr}...),
libp2p.PrivateNetwork(prot),
libp2p.NATPortMap(),
)
}
// EncodeProtectorKey converts a byte slice to its hex string representation.
func EncodeProtectorKey(secretBytes []byte) string {
return hex.EncodeToString(secretBytes)
}