-
Notifications
You must be signed in to change notification settings - Fork 6
/
host.go
347 lines (288 loc) · 8.41 KB
/
host.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package host
import (
"context"
"crypto/rand"
"fmt"
"os"
"strings"
"time"
rpcHost "github.com/agencyenterprise/go-libp2p-pubsub-benchmark-tools/pkg/grpc/host"
"github.com/agencyenterprise/go-libp2p-pubsub-benchmark-tools/pkg/host/config"
"github.com/agencyenterprise/go-libp2p-pubsub-benchmark-tools/pkg/logger"
ipfsaddr "github.com/ipfs/go-ipfs-addr"
"github.com/libp2p/go-libp2p"
connmgr "github.com/libp2p/go-libp2p-connmgr"
lcrypto "github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/routing"
kaddht "github.com/libp2p/go-libp2p-kad-dht"
peerstore "github.com/libp2p/go-libp2p-peerstore"
pubsub "github.com/libp2p/go-libp2p-pubsub"
lconfig "github.com/libp2p/go-libp2p/config"
"github.com/libp2p/go-libp2p/p2p/discovery"
)
type mdnsNotifee struct {
h host.Host
ctx context.Context
}
// HandlePeerFound...
func (m *mdnsNotifee) HandlePeerFound(pi peer.AddrInfo) {
if err := m.h.Connect(m.ctx, pi); err != nil {
logger.Warnf("mdns err connecting to peer with id %v:\n%v", pi.ID, err)
}
}
// New returns a new host
// note: not passing reference to config because want it to be read only.
func New(ctx context.Context, conf config.Config) (*Host, error) {
h := &Host{
ctx: ctx,
conf: conf,
shtDwn: make(chan struct{}),
}
var lOpts []lconfig.Option
// add private key
if conf.Host.Priv == nil {
var (
priv lcrypto.PrivKey
err error
)
switch strings.ToLower(conf.Host.KeyType) {
case "ecdsa":
logger.Info("host priv key type is ECDSA")
priv, _, err = lcrypto.GenerateECDSAKeyPair(rand.Reader)
case "ed255199":
logger.Info("host priv key type is Ed25519")
priv, _, err = lcrypto.GenerateEd25519Key(rand.Reader)
case "rsa":
logger.Infof("host priv key type is RSA with %d bits", conf.Host.RSABits)
priv, _, err = lcrypto.GenerateRSAKeyPair(conf.Host.RSABits, rand.Reader)
case "secp256k1":
logger.Info("host priv key type is Secp256k1")
priv, _, err = lcrypto.GenerateSecp256k1Key(rand.Reader)
default:
logger.Errorf("%s is not a supported private key type", conf.Host.KeyType)
err = config.ErrUnsupportedKeyType
}
if err != nil {
logger.Errorf("err generating private key:\n%v", err)
return nil, err
}
lOpts = append(lOpts, libp2p.Identity(priv))
} else {
lOpts = append(lOpts, libp2p.Identity(conf.Host.Priv))
}
// create transports
transports, err := parseTransportOptions(conf.Host.Transports)
if err != nil {
logger.Errorf("err parsing transports\n%v", err)
return nil, err
}
lOpts = append(lOpts, transports)
// create muxers
muxers, err := parseMuxerOptions(conf.Host.Muxers)
if err != nil {
logger.Errorf("err parsing muxers\n%v", err)
return nil, err
}
lOpts = append(lOpts, muxers)
// create security
security, err := parseSecurityOptions(conf.Host.Security)
if err != nil {
logger.Errorf("err parsing security\n%v", err)
return nil, err
}
lOpts = append(lOpts, security)
// add listen addresses
if len(conf.Host.Listens) > 0 {
lOpts = append(lOpts, libp2p.ListenAddrStrings(conf.Host.Listens...))
}
// Conn manager
if !conf.Host.OmitConnectionManager {
cm := connmgr.NewConnManager(256, 512, 120)
lOpts = append(lOpts, libp2p.ConnectionManager(cm))
}
// NAT port map
if !conf.Host.OmitNATPortMap {
lOpts = append(lOpts, libp2p.NATPortMap())
}
// create router
if !conf.Host.OmitRouting {
newDHT := func(hst host.Host) (routing.PeerRouting, error) {
var err error
dht, err := kaddht.New(ctx, hst)
if err != nil {
logger.Errorf("err creating new kaddht\n%v", err)
}
h.router = dht
return dht, err
}
routing := libp2p.Routing(newDHT)
lOpts = append(lOpts, routing)
}
if conf.Host.OmitRelay {
lOpts = append(lOpts, libp2p.DisableRelay())
}
// build the libp2p host
host, err := libp2p.New(ctx, lOpts...)
if err != nil {
logger.Errorf("err creating new libp2p host\n%v", err)
return nil, err
}
h.host = host
return h, nil
}
// ID returns the host's id
func (h *Host) ID() string {
return h.host.ID().Pretty()
}
// Addresses returns the listening addresses of the host
func (h *Host) Addresses() []string {
var addresses []string
for _, addr := range h.host.Addrs() {
addresses = append(addresses, fmt.Sprintf("%s", addr))
}
return addresses
}
// IPFSAddresses returns the ipfs listening addresses of the host
func (h *Host) IPFSAddresses() []string {
var addresses []string
for _, addr := range h.host.Addrs() {
addresses = append(addresses, fmt.Sprintf("%s/ipfs/%s", addr, h.host.ID().Pretty()))
}
return addresses
}
// RPCAddress returns the host rpc address
func (h *Host) RPCAddress() string {
return h.conf.Host.RPCAddress
}
// Connect connects the host to the list of peers
// note: it expects the peers to be in IPFS form
func (h *Host) Connect(peers []string) error {
for _, p := range peers {
addr, err := ipfsaddr.ParseString(p)
if err != nil || addr == nil {
logger.Errorf("err parsing peer: %s\n%v", p, err)
return err
}
pinfo, err := peerstore.InfoFromP2pAddr(addr.Multiaddr())
if err != nil || pinfo == nil {
logger.Errorf("err getting info from peerstore\n%v", err)
return err
}
logger.Infof("full peer addr: %s", addr.String())
logger.Infof("peer info: %v", pinfo)
if err := h.host.Connect(h.ctx, *pinfo); err != nil {
logger.Errorf("connecting to peer failed\n%v", err)
return err
}
logger.Infof("Connected to peer: %v", pinfo.ID)
}
return nil
}
// BuildPubSub returns a pubsub service
func (h *Host) BuildPubSub() (*pubsub.PubSub, error) {
var (
ps *pubsub.PubSub
err error
)
// build the gossip pub/sub
switch strings.ToLower(h.conf.Host.PubsubAlgorithm) {
case "gossip":
logger.Info("building gossip pubsub")
ps, err = pubsub.NewGossipSub(h.ctx, h.host)
case "flood":
logger.Info("building flood pubsub")
ps, err = pubsub.NewFloodSub(h.ctx, h.host)
case "random":
logger.Info("building random pubsub")
ps, err = pubsub.NewRandomSub(h.ctx, h.host)
default:
logger.Errorf("err, the pubsub algorithm %s is not recognized", h.conf.Host.PubsubAlgorithm)
return nil, ErrUnknownPubsubAlgorithm
}
if err != nil {
logger.Errorf("err creating new pub sub\n%v", err)
return nil, err
}
// subscribe to the topic
_, err = ps.Subscribe(pubsubTopic)
if err != nil {
logger.Errorf("err subscribing\n%v", err)
return nil, err
}
if err = ps.RegisterTopicValidator(pubsubTopic, buildValidator(h.host.ID())); err != nil {
logger.Errorf("err registering valudator:\n%v", err)
return nil, err
}
return ps, nil
}
// BuildRPC returns an rpc service
func (h *Host) BuildRPC(ch chan error, ps *pubsub.PubSub) error {
// Start the RPC server
rHost := rpcHost.New(&rpcHost.Props{
Host: h.host,
CH: ch,
PS: ps,
PubsubTopic: pubsubTopic,
CTX: h.ctx,
Shutdown: h.shtDwn,
})
go func(rh *rpcHost.Host, c chan error) {
if err := rh.Listen(h.ctx, h.conf.Host.RPCAddress); err != nil {
logger.Errorf("err listening on rpc:\n%v", err)
c <- err
}
}(rHost, ch)
return nil
}
// BuildDiscoveryAndRouting ...
func (h *Host) BuildDiscoveryAndRouting() error {
// create discovery service
if !h.conf.Host.OmitDiscoveryService {
mdns, err := discovery.NewMdnsService(h.ctx, h.host, time.Second*10, "")
if err != nil {
logger.Errorf("err discovering\n%v", err)
return err
}
mdns.RegisterNotifee(&mdnsNotifee{h: h.host, ctx: h.ctx})
}
if !h.conf.Host.OmitRouting {
if h.router == nil {
return ErrNilRouter
}
if err := h.router.Bootstrap(h.ctx); err != nil {
logger.Errorf("err bootstrapping\n%v", err)
return err
}
}
return nil
}
// Start starts a new pubsub host
func (h *Host) Start(ch chan error, stop chan os.Signal) error {
for i, addr := range h.host.Addrs() {
logger.Infof("listening #%d on: %s/ipfs/%s\n", i, addr, h.host.ID().Pretty())
}
defer func() {
if err := h.host.Close(); err != nil {
logger.Errorf("err closing host:\n%v", err)
}
}()
select {
case <-stop:
// note: I don't like '^C' showing up on the same line as the next logged line...
fmt.Println("")
logger.Info("Received stop signal from os. Shutting down...")
case <-h.shtDwn:
logger.Info("received shutdown signal on rpc")
case err := <-ch:
logger.Errorf("received err on rpc channel:\n%v", err)
return err
case <-h.ctx.Done():
if err := h.ctx.Err(); err != nil {
logger.Errorf("err on the context:\n%v", err)
return err
}
}
return nil
}