-
Notifications
You must be signed in to change notification settings - Fork 199
/
netMessenger.go
582 lines (468 loc) · 15.6 KB
/
netMessenger.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package libp2p
import (
"context"
"fmt"
"sync"
"time"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/core/throttler"
"github.com/ElrondNetwork/elrond-go/logger"
"github.com/ElrondNetwork/elrond-go/p2p"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/connmgr"
libp2pCrypto "github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
"github.com/libp2p/go-libp2p-pubsub"
)
var sendTimeout = time.Microsecond * 100
// ListenAddrWithIp4AndTcp defines the listening address with ip v.4 and TCP
const ListenAddrWithIp4AndTcp = "/ip4/0.0.0.0/tcp/"
// ListenLocalhostAddrWithIp4AndTcp defines the local host listening ip v.4 address and TCP
const ListenLocalhostAddrWithIp4AndTcp = "/ip4/127.0.0.1/tcp/"
// DirectSendID represents the protocol ID for sending and receiving direct P2P messages
const DirectSendID = protocol.ID("/directsend/1.0.0")
const refreshPeersOnTopic = time.Second * 60
const ttlPeersOnTopic = time.Second * 120
const pubsubTimeCacheDuration = 10 * time.Minute
const broadcastGoRoutines = 1000
const defaultThresholdMinConnectedPeers = 3
//TODO remove the header size of the message when commit d3c5ecd3a3e884206129d9f2a9a4ddfd5e7c8951 from
// https://github.com/libp2p/go-libp2p-pubsub/pull/189/commits will be part of a new release
var messageHeader = 64 * 1024 //64kB
var maxSendBuffSize = (1 << 20) - messageHeader
var log = logger.GetOrCreate("p2p/libp2p")
//TODO refactor this struct to have be a wrapper (with logic) over a glue code
type networkMessenger struct {
ctxProvider *Libp2pContext
pb *pubsub.PubSub
ds p2p.DirectSender
connMonitor *libp2pConnectionMonitor
peerDiscoverer p2p.PeerDiscoverer
mutTopics sync.RWMutex
topics map[string]*pubsub.Topic
processors map[string]p2p.MessageProcessor
outgoingPLB p2p.ChannelLoadBalancer
poc *peersOnChannel
goRoutinesThrottler *throttler.NumGoRoutineThrottler
}
// NewNetworkMessenger creates a libP2P messenger by opening a port on the current machine
// Should be used in production!
func NewNetworkMessenger(
ctx context.Context,
port int,
p2pPrivKey libp2pCrypto.PrivKey,
conMgr connmgr.ConnManager,
outgoingPLB p2p.ChannelLoadBalancer,
peerDiscoverer p2p.PeerDiscoverer,
listenAddress string,
targetConnCount int,
) (*networkMessenger, error) {
if ctx == nil {
return nil, p2p.ErrNilContext
}
if port < 0 {
return nil, p2p.ErrInvalidPort
}
if p2pPrivKey == nil {
return nil, p2p.ErrNilP2PprivateKey
}
if outgoingPLB == nil || outgoingPLB.IsInterfaceNil() {
return nil, p2p.ErrNilChannelLoadBalancer
}
if peerDiscoverer == nil || peerDiscoverer.IsInterfaceNil() {
return nil, p2p.ErrNilPeerDiscoverer
}
address := fmt.Sprintf(listenAddress+"%d", port)
opts := []libp2p.Option{
libp2p.ListenAddrStrings(address),
libp2p.Identity(p2pPrivKey),
libp2p.DefaultMuxers,
libp2p.DefaultSecurity,
libp2p.ConnectionManager(conMgr),
libp2p.DefaultTransports,
//we need the disable relay option in order to save the node's bandwidth as much as possible
libp2p.DisableRelay(),
libp2p.NATPortMap(),
}
h, err := libp2p.New(ctx, opts...)
if err != nil {
return nil, err
}
lctx, err := NewLibp2pContext(ctx, NewConnectableHost(h))
if err != nil {
log.LogIfError(h.Close())
return nil, err
}
p2pNode, err := createMessenger(lctx, true, outgoingPLB, peerDiscoverer, targetConnCount)
if err != nil {
log.LogIfError(h.Close())
return nil, err
}
goRoutinesThrottler, err := throttler.NewNumGoRoutineThrottler(broadcastGoRoutines)
if err != nil {
log.LogIfError(h.Close())
return nil, err
}
p2pNode.goRoutinesThrottler = goRoutinesThrottler
return p2pNode, nil
}
func createMessenger(
lctx *Libp2pContext,
withSigning bool,
outgoingPLB p2p.ChannelLoadBalancer,
peerDiscoverer p2p.PeerDiscoverer,
targetConnCount int,
) (*networkMessenger, error) {
pb, err := createPubSub(lctx, withSigning)
if err != nil {
return nil, err
}
err = peerDiscoverer.ApplyContext(lctx)
if err != nil {
return nil, err
}
reconnecter, _ := peerDiscoverer.(p2p.Reconnecter)
netMes := networkMessenger{
ctxProvider: lctx,
pb: pb,
topics: make(map[string]*pubsub.Topic),
processors: make(map[string]p2p.MessageProcessor),
outgoingPLB: outgoingPLB,
peerDiscoverer: peerDiscoverer,
}
netMes.connMonitor, err = newLibp2pConnectionMonitor(reconnecter, defaultThresholdMinConnectedPeers, targetConnCount)
if err != nil {
return nil, err
}
lctx.connHost.Network().Notify(netMes.connMonitor)
netMes.ds, err = NewDirectSender(lctx.Context(), lctx.Host(), netMes.directMessageHandler)
if err != nil {
return nil, err
}
netMes.poc, err = newPeersOnChannel(
pb.ListPeers,
refreshPeersOnTopic,
ttlPeersOnTopic)
if err != nil {
return nil, err
}
go func(pubsub *pubsub.PubSub, plb p2p.ChannelLoadBalancer) {
for {
netMes.sendMessage()
}
}(pb, netMes.outgoingPLB)
addresses := make([]interface{}, 0)
for i, address := range netMes.ctxProvider.Host().Addrs() {
addresses = append(addresses, fmt.Sprintf("addr%d", i))
addresses = append(addresses, address.String()+"/p2p/"+netMes.ID().Pretty())
}
log.Info("listening on addresses", addresses...)
return &netMes, nil
}
func createPubSub(ctxProvider *Libp2pContext, withSigning bool) (*pubsub.PubSub, error) {
optsPS := []pubsub.Option{
pubsub.WithMessageSigning(withSigning),
}
pubsub.TimeCacheDuration = pubsubTimeCacheDuration
ps, err := pubsub.NewGossipSub(ctxProvider.Context(), ctxProvider.Host(), optsPS...)
if err != nil {
return nil, err
}
return ps, nil
}
func (netMes *networkMessenger) sendMessage() {
sendableData := netMes.outgoingPLB.CollectOneElementFromChannels()
if sendableData == nil {
return
}
netMes.mutTopics.RLock()
topic := netMes.topics[sendableData.Topic]
netMes.mutTopics.RUnlock()
if topic == nil {
log.Debug("topic not joined",
"topic", sendableData.Topic)
return
}
ctx, cancelFunc := context.WithTimeout(context.Background(), sendTimeout)
defer cancelFunc()
err := topic.Publish(ctx, sendableData.Buff)
if err != nil {
log.Trace("error sending data",
"error", err)
}
}
// Close closes the host, connections and streams
func (netMes *networkMessenger) Close() error {
return netMes.ctxProvider.Host().Close()
}
// ID returns the messenger's ID
func (netMes *networkMessenger) ID() p2p.PeerID {
h := netMes.ctxProvider.Host()
return p2p.PeerID(h.ID())
}
// Peers returns the list of all known peers ID (including self)
func (netMes *networkMessenger) Peers() []p2p.PeerID {
h := netMes.ctxProvider.Host()
peers := make([]p2p.PeerID, 0)
for _, p := range h.Peerstore().Peers() {
peers = append(peers, p2p.PeerID(p))
}
return peers
}
// Addresses returns all addresses found in peerstore
func (netMes *networkMessenger) Addresses() []string {
h := netMes.ctxProvider.Host()
addrs := make([]string, 0)
for _, address := range h.Addrs() {
addrs = append(addrs, address.String()+"/p2p/"+netMes.ID().Pretty())
}
return addrs
}
// ConnectToPeer tries to open a new connection to a peer
func (netMes *networkMessenger) ConnectToPeer(address string) error {
h := netMes.ctxProvider.Host()
ctx := netMes.ctxProvider.ctx
return h.ConnectToPeer(ctx, address)
}
// TrimConnections will trigger a manual sweep onto current connection set reducing the
// number of connections if needed
func (netMes *networkMessenger) TrimConnections() {
h := netMes.ctxProvider.Host()
ctx := netMes.ctxProvider.Context()
h.ConnManager().TrimOpenConns(ctx)
}
// Bootstrap will start the peer discovery mechanism
func (netMes *networkMessenger) Bootstrap() error {
return netMes.peerDiscoverer.Bootstrap()
}
// IsConnected returns true if current node is connected to provided peer
func (netMes *networkMessenger) IsConnected(peerID p2p.PeerID) bool {
h := netMes.ctxProvider.Host()
connectedness := h.Network().Connectedness(peer.ID(peerID))
return connectedness == network.Connected
}
// ConnectedPeers returns the current connected peers list
func (netMes *networkMessenger) ConnectedPeers() []p2p.PeerID {
h := netMes.ctxProvider.Host()
connectedPeers := make(map[p2p.PeerID]struct{})
for _, conn := range h.Network().Conns() {
p := p2p.PeerID(conn.RemotePeer())
if netMes.IsConnected(p) {
connectedPeers[p] = struct{}{}
}
}
peerList := make([]p2p.PeerID, len(connectedPeers))
index := 0
for k := range connectedPeers {
peerList[index] = k
index++
}
return peerList
}
// ConnectedAddresses returns all connected peer's addresses
func (netMes *networkMessenger) ConnectedAddresses() []string {
h := netMes.ctxProvider.Host()
conns := make([]string, 0)
for _, c := range h.Network().Conns() {
conns = append(conns, c.RemoteMultiaddr().String()+"/p2p/"+c.RemotePeer().Pretty())
}
return conns
}
// PeerAddress returns the peer's address or empty string if the peer is unknown
func (netMes *networkMessenger) PeerAddress(pid p2p.PeerID) string {
h := netMes.ctxProvider.Host()
//check if the peer is connected to return it's connected address
for _, c := range h.Network().Conns() {
if string(c.RemotePeer()) == string(pid.Bytes()) {
return c.RemoteMultiaddr().String()
}
}
//check in peerstore (maybe it is known but not connected)
addresses := h.Peerstore().Addrs(peer.ID(pid.Bytes()))
if len(addresses) == 0 {
return ""
}
//return the first address from multi address slice
return addresses[0].String()
}
// ConnectedPeersOnTopic returns the connected peers on a provided topic
func (netMes *networkMessenger) ConnectedPeersOnTopic(topic string) []p2p.PeerID {
return netMes.poc.ConnectedPeersOnChannel(topic)
}
// CreateTopic opens a new topic using pubsub infrastructure
func (netMes *networkMessenger) CreateTopic(name string, createChannelForTopic bool) error {
ctx := netMes.ctxProvider.Context()
netMes.mutTopics.Lock()
_, found := netMes.topics[name]
if found {
netMes.mutTopics.Unlock()
return p2p.ErrTopicAlreadyExists
}
netMes.topics[name] = nil
topic, err := netMes.pb.Join(name)
if err != nil {
netMes.mutTopics.Unlock()
return err
}
subscrRequest, err := topic.Subscribe()
if err != nil {
netMes.mutTopics.Unlock()
return err
}
netMes.topics[name] = topic
netMes.mutTopics.Unlock()
if createChannelForTopic {
err = netMes.outgoingPLB.AddChannel(name)
}
//just a dummy func to consume messages received by the newly created topic
go func() {
for {
_, _ = subscrRequest.Next(ctx)
}
}()
return err
}
// HasTopic returns true if the topic has been created
func (netMes *networkMessenger) HasTopic(name string) bool {
netMes.mutTopics.RLock()
_, found := netMes.topics[name]
netMes.mutTopics.RUnlock()
return found
}
// HasTopicValidator returns true if the topic has a validator set
func (netMes *networkMessenger) HasTopicValidator(name string) bool {
netMes.mutTopics.RLock()
validator := netMes.processors[name]
netMes.mutTopics.RUnlock()
return validator != nil
}
// OutgoingChannelLoadBalancer returns the channel load balancer object used by the messenger to send data
func (netMes *networkMessenger) OutgoingChannelLoadBalancer() p2p.ChannelLoadBalancer {
return netMes.outgoingPLB
}
// BroadcastOnChannelBlocking tries to send a byte buffer onto a topic using provided channel
// It is a blocking method. It needs to be launched on a go routine
func (netMes *networkMessenger) BroadcastOnChannelBlocking(channel string, topic string, buff []byte) error {
if len(buff) > maxSendBuffSize {
return p2p.ErrMessageTooLarge
}
if !netMes.goRoutinesThrottler.CanProcess() {
return p2p.ErrTooManyGoroutines
}
netMes.goRoutinesThrottler.StartProcessing()
sendable := &p2p.SendableData{
Buff: buff,
Topic: topic,
}
netMes.outgoingPLB.GetChannelOrDefault(channel) <- sendable
netMes.goRoutinesThrottler.EndProcessing()
return nil
}
// BroadcastOnChannel tries to send a byte buffer onto a topic using provided channel
func (netMes *networkMessenger) BroadcastOnChannel(channel string, topic string, buff []byte) {
go func() {
err := netMes.BroadcastOnChannelBlocking(channel, topic, buff)
if err != nil {
log.Debug("p2p broadcast", "error", err.Error())
}
}()
}
// Broadcast tries to send a byte buffer onto a topic using the topic name as channel
func (netMes *networkMessenger) Broadcast(topic string, buff []byte) {
netMes.BroadcastOnChannel(topic, topic, buff)
}
// RegisterMessageProcessor registers a message process on a topic
func (netMes *networkMessenger) RegisterMessageProcessor(topic string, handler p2p.MessageProcessor) error {
if check.IfNil(handler) {
return p2p.ErrNilValidator
}
netMes.mutTopics.Lock()
defer netMes.mutTopics.Unlock()
_, found := netMes.topics[topic]
if !found {
return p2p.ErrNilTopic
}
validator := netMes.processors[topic]
if validator != nil {
return p2p.ErrTopicValidatorOperationNotSupported
}
broadcastHandler := func(buffToSend []byte) {
netMes.Broadcast(topic, buffToSend)
}
err := netMes.pb.RegisterTopicValidator(topic, func(ctx context.Context, pid peer.ID, message *pubsub.Message) bool {
err := handler.ProcessReceivedMessage(NewMessage(message), broadcastHandler)
if err != nil {
log.Trace("p2p validator", "error", err.Error(), "topics", message.TopicIDs)
}
return err == nil
})
if err != nil {
return err
}
netMes.processors[topic] = handler
return nil
}
// UnregisterMessageProcessor registers a message processes on a topic
func (netMes *networkMessenger) UnregisterMessageProcessor(topic string) error {
netMes.mutTopics.Lock()
defer netMes.mutTopics.Unlock()
_, found := netMes.topics[topic]
if !found {
return p2p.ErrNilTopic
}
validator := netMes.processors[topic]
if validator == nil {
return p2p.ErrTopicValidatorOperationNotSupported
}
err := netMes.pb.UnregisterTopicValidator(topic)
if err != nil {
return err
}
netMes.topics[topic] = nil
return nil
}
// SendToConnectedPeer sends a direct message to a connected peer
func (netMes *networkMessenger) SendToConnectedPeer(topic string, buff []byte, peerID p2p.PeerID) error {
return netMes.ds.Send(topic, buff, peerID)
}
func (netMes *networkMessenger) directMessageHandler(message p2p.MessageP2P) error {
var processor p2p.MessageProcessor
netMes.mutTopics.RLock()
processor = netMes.processors[message.TopicIDs()[0]]
netMes.mutTopics.RUnlock()
if processor == nil {
return p2p.ErrNilValidator
}
go func(msg p2p.MessageP2P) {
err := processor.ProcessReceivedMessage(msg, nil)
if err != nil {
log.Trace("p2p validator", "error", err.Error(), "topics", msg.TopicIDs())
}
}(message)
return nil
}
// IsConnectedToTheNetwork returns true if the current node is connected to the network
func (netMes *networkMessenger) IsConnectedToTheNetwork() bool {
netw := netMes.ctxProvider.connHost.Network()
return netMes.connMonitor.isConnectedToTheNetwork(netw)
}
// SetThresholdMinConnectedPeers sets the minimum connected peers before triggering a new reconnection
func (netMes *networkMessenger) SetThresholdMinConnectedPeers(minConnectedPeers int) error {
if minConnectedPeers < 0 {
return p2p.ErrInvalidValue
}
netw := netMes.ctxProvider.connHost.Network()
netMes.connMonitor.thresholdMinConnectedPeers = minConnectedPeers
netMes.connMonitor.doReconnectionIfNeeded(netw)
return nil
}
// ThresholdMinConnectedPeers returns the minimum connected peers before triggering a new reconnection
func (netMes *networkMessenger) ThresholdMinConnectedPeers() int {
return netMes.connMonitor.thresholdMinConnectedPeers
}
// IsInterfaceNil returns true if there is no value under the interface
func (netMes *networkMessenger) IsInterfaceNil() bool {
return netMes == nil
}