-
Notifications
You must be signed in to change notification settings - Fork 202
/
netMessenger.go
1384 lines (1154 loc) · 41 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package libp2p
import (
"context"
"crypto/ecdsa"
"encoding/hex"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/core/throttler"
logger "github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/common"
"github.com/ElrondNetwork/elrond-go/config"
p2pDebug "github.com/ElrondNetwork/elrond-go/debug/p2p"
"github.com/ElrondNetwork/elrond-go/p2p"
"github.com/ElrondNetwork/elrond-go/p2p/data"
"github.com/ElrondNetwork/elrond-go/p2p/libp2p/connectionMonitor"
"github.com/ElrondNetwork/elrond-go/p2p/libp2p/disabled"
discoveryFactory "github.com/ElrondNetwork/elrond-go/p2p/libp2p/discovery/factory"
"github.com/ElrondNetwork/elrond-go/p2p/libp2p/metrics"
metricsFactory "github.com/ElrondNetwork/elrond-go/p2p/libp2p/metrics/factory"
"github.com/ElrondNetwork/elrond-go/p2p/libp2p/networksharding/factory"
randFactory "github.com/ElrondNetwork/elrond-go/p2p/libp2p/rand/factory"
"github.com/ElrondNetwork/elrond-go/p2p/loadBalancer"
pubsub "github.com/ElrondNetwork/go-libp2p-pubsub"
pubsubPb "github.com/ElrondNetwork/go-libp2p-pubsub/pb"
"github.com/btcsuite/btcd/btcec"
logging "github.com/ipfs/go-log"
"github.com/libp2p/go-libp2p"
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"
)
const (
// ListenAddrWithIp4AndTcp defines the listening address with ip v.4 and TCP
ListenAddrWithIp4AndTcp = "/ip4/0.0.0.0/tcp/"
// ListenLocalhostAddrWithIp4AndTcp defines the local host listening ip v.4 address and TCP
ListenLocalhostAddrWithIp4AndTcp = "/ip4/127.0.0.1/tcp/"
// DirectSendID represents the protocol ID for sending and receiving direct P2P messages
DirectSendID = protocol.ID("/erd/directsend/1.0.0")
durationBetweenSends = time.Microsecond * 10
durationCheckConnections = time.Second
refreshPeersOnTopic = time.Second * 3
ttlPeersOnTopic = time.Second * 10
ttlConnectionsWatcher = time.Hour * 2
pubsubTimeCacheDuration = 10 * time.Minute
acceptMessagesInAdvanceDuration = 20 * time.Second // we are accepting the messages with timestamp in the future only for this delta
pollWaitForConnectionsInterval = time.Second
broadcastGoRoutines = 1000
timeBetweenPeerPrints = time.Second * 20
timeBetweenExternalLoggersCheck = time.Second * 20
minRangePortValue = 1025
noSignPolicy = pubsub.MessageSignaturePolicy(0) // should be used only in tests
msgBindError = "address already in use"
maxRetriesIfBindError = 10
)
type messageSigningConfig bool
const (
withMessageSigning messageSigningConfig = true
withoutMessageSigning messageSigningConfig = false
)
// 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 << 21) - messageHeader
var log = logger.GetOrCreate("p2p/libp2p")
var _ p2p.Messenger = (*networkMessenger)(nil)
var externalPackages = []string{"dht", "nat", "basichost", "pubsub"}
func init() {
pubsub.TimeCacheDuration = pubsubTimeCacheDuration
for _, external := range externalPackages {
_ = logger.GetOrCreate(fmt.Sprintf("external/%s", external))
}
}
// TODO refactor this struct to have be a wrapper (with logic) over a glue code
type networkMessenger struct {
*p2pSigner
ctx context.Context
cancelFunc context.CancelFunc
p2pHost ConnectableHost
port int
pb *pubsub.PubSub
ds p2p.DirectSender
// TODO refactor this (connMonitor & connMonitorWrapper)
connMonitor ConnectionMonitor
connMonitorWrapper p2p.ConnectionMonitorWrapper
peerDiscoverer p2p.PeerDiscoverer
sharder p2p.Sharder
peerShardResolver p2p.PeerShardResolver
mutPeerResolver sync.RWMutex
mutTopics sync.RWMutex
processors map[string]*topicProcessors
topics map[string]*pubsub.Topic
subscriptions map[string]*pubsub.Subscription
outgoingPLB p2p.ChannelLoadBalancer
poc *peersOnChannel
goRoutinesThrottler *throttler.NumGoRoutinesThrottler
connectionsMetric *metrics.Connections
debugger p2p.Debugger
marshalizer p2p.Marshalizer
syncTimer p2p.SyncTimer
preferredPeersHolder p2p.PreferredPeersHolderHandler
printConnectionsWatcher p2p.ConnectionsWatcher
peersRatingHandler p2p.PeersRatingHandler
mutPeerTopicNotifiers sync.RWMutex
peerTopicNotifiers []p2p.PeerTopicNotifier
}
// ArgsNetworkMessenger defines the options used to create a p2p wrapper
type ArgsNetworkMessenger struct {
ListenAddress string
Marshalizer p2p.Marshalizer
P2pConfig config.P2PConfig
SyncTimer p2p.SyncTimer
PreferredPeersHolder p2p.PreferredPeersHolderHandler
NodeOperationMode p2p.NodeOperation
PeersRatingHandler p2p.PeersRatingHandler
ConnectionWatcherType string
}
// NewNetworkMessenger creates a libP2P messenger by opening a port on the current machine
func NewNetworkMessenger(args ArgsNetworkMessenger) (*networkMessenger, error) {
return newNetworkMessenger(args, withMessageSigning)
}
func newNetworkMessenger(args ArgsNetworkMessenger, messageSigning messageSigningConfig) (*networkMessenger, error) {
if check.IfNil(args.Marshalizer) {
return nil, fmt.Errorf("%w when creating a new network messenger", p2p.ErrNilMarshalizer)
}
if check.IfNil(args.SyncTimer) {
return nil, fmt.Errorf("%w when creating a new network messenger", p2p.ErrNilSyncTimer)
}
if check.IfNil(args.PreferredPeersHolder) {
return nil, fmt.Errorf("%w when creating a new network messenger", p2p.ErrNilPreferredPeersHolder)
}
if check.IfNil(args.PeersRatingHandler) {
return nil, fmt.Errorf("%w when creating a new network messenger", p2p.ErrNilPeersRatingHandler)
}
p2pPrivKey, err := createP2PPrivKey(args.P2pConfig.Node.Seed)
if err != nil {
return nil, err
}
setupExternalP2PLoggers()
p2pNode, err := constructNodeWithPortRetry(args, p2pPrivKey)
if err != nil {
return nil, err
}
err = addComponentsToNode(args, p2pNode, messageSigning)
if err != nil {
log.LogIfError(p2pNode.p2pHost.Close())
return nil, err
}
return p2pNode, nil
}
func constructNode(
args ArgsNetworkMessenger,
p2pPrivKey *libp2pCrypto.Secp256k1PrivateKey,
) (*networkMessenger, error) {
port, err := getPort(args.P2pConfig.Node.Port, checkFreePort)
if err != nil {
return nil, err
}
log.Debug("connectionWatcherType", "type", args.ConnectionWatcherType)
connWatcher, err := metricsFactory.NewConnectionsWatcher(args.ConnectionWatcherType, ttlConnectionsWatcher)
if err != nil {
return nil, err
}
address := fmt.Sprintf(args.ListenAddress+"%d", port)
opts := []libp2p.Option{
libp2p.ListenAddrStrings(address),
libp2p.Identity(p2pPrivKey),
libp2p.DefaultMuxers,
libp2p.DefaultSecurity,
libp2p.DefaultTransports,
// we need the disable relay option in order to save the node's bandwidth as much as possible
libp2p.DisableRelay(),
libp2p.NATPortMap(),
}
ctx, cancelFunc := context.WithCancel(context.Background())
h, err := libp2p.New(opts...)
if err != nil {
cancelFunc()
return nil, err
}
p2pNode := &networkMessenger{
p2pSigner: &p2pSigner{
privateKey: p2pPrivKey,
},
ctx: ctx,
cancelFunc: cancelFunc,
p2pHost: NewConnectableHost(h),
port: port,
printConnectionsWatcher: connWatcher,
peersRatingHandler: args.PeersRatingHandler,
peerTopicNotifiers: make([]p2p.PeerTopicNotifier, 0),
}
return p2pNode, nil
}
func constructNodeWithPortRetry(
args ArgsNetworkMessenger,
p2pPrivKey *libp2pCrypto.Secp256k1PrivateKey,
) (*networkMessenger, error) {
var lastErr error
for i := 0; i < maxRetriesIfBindError; i++ {
p2pNode, err := constructNode(args, p2pPrivKey)
if err == nil {
return p2pNode, nil
}
lastErr = err
if !strings.Contains(err.Error(), msgBindError) {
// not a bind error, return directly
return nil, err
}
log.Debug("bind error in network messenger", "retry number", i+1, "error", err)
}
return nil, lastErr
}
func setupExternalP2PLoggers() {
for _, external := range externalPackages {
logLevel := logger.GetLoggerLogLevel("external/" + external)
if logLevel > logger.LogTrace {
continue
}
_ = logging.SetLogLevel(external, "DEBUG")
}
}
func createP2PPrivKey(seed string) (*libp2pCrypto.Secp256k1PrivateKey, error) {
randReader, err := randFactory.NewRandFactory(seed)
if err != nil {
return nil, err
}
prvKey, _ := ecdsa.GenerateKey(btcec.S256(), randReader)
return (*libp2pCrypto.Secp256k1PrivateKey)(prvKey), nil
}
func addComponentsToNode(
args ArgsNetworkMessenger,
p2pNode *networkMessenger,
messageSigning messageSigningConfig,
) error {
var err error
p2pNode.processors = make(map[string]*topicProcessors)
p2pNode.topics = make(map[string]*pubsub.Topic)
p2pNode.subscriptions = make(map[string]*pubsub.Subscription)
p2pNode.outgoingPLB = loadBalancer.NewOutgoingChannelLoadBalancer()
p2pNode.peerShardResolver = &unknownPeerShardResolver{}
p2pNode.marshalizer = args.Marshalizer
p2pNode.syncTimer = args.SyncTimer
p2pNode.preferredPeersHolder = args.PreferredPeersHolder
p2pNode.debugger = p2pDebug.NewP2PDebugger(core.PeerID(p2pNode.p2pHost.ID()))
p2pNode.peersRatingHandler = args.PeersRatingHandler
err = p2pNode.createPubSub(messageSigning)
if err != nil {
return err
}
err = p2pNode.createSharder(args)
if err != nil {
return err
}
err = p2pNode.createDiscoverer(args.P2pConfig)
if err != nil {
return err
}
err = p2pNode.createConnectionMonitor(args.P2pConfig)
if err != nil {
return err
}
p2pNode.createConnectionsMetric()
p2pNode.ds, err = NewDirectSender(p2pNode.ctx, p2pNode.p2pHost, p2pNode.directMessageHandler)
if err != nil {
return err
}
p2pNode.goRoutinesThrottler, err = throttler.NewNumGoRoutinesThrottler(broadcastGoRoutines)
if err != nil {
return err
}
p2pNode.printLogs()
return nil
}
func (netMes *networkMessenger) createPubSub(messageSigning messageSigningConfig) error {
optsPS := make([]pubsub.Option, 0)
if messageSigning == withoutMessageSigning {
log.Warn("signature verification is turned off in network messenger instance. NOT recommended in production environment")
optsPS = append(optsPS, pubsub.WithMessageSignaturePolicy(noSignPolicy))
}
optsPS = append(optsPS, pubsub.WithPeerFilter(netMes.newPeerFound))
var err error
netMes.pb, err = pubsub.NewGossipSub(netMes.ctx, netMes.p2pHost, optsPS...)
if err != nil {
return err
}
netMes.poc, err = newPeersOnChannel(
netMes.peersRatingHandler,
netMes.pb.ListPeers,
refreshPeersOnTopic,
ttlPeersOnTopic)
if err != nil {
return err
}
go func(plb p2p.ChannelLoadBalancer) {
for {
select {
case <-time.After(durationBetweenSends):
case <-netMes.ctx.Done():
log.Debug("closing networkMessenger's send from channel load balancer go routine")
return
}
sendableData := plb.CollectOneElementFromChannels()
if sendableData == nil {
continue
}
netMes.mutTopics.RLock()
topic := netMes.topics[sendableData.Topic]
netMes.mutTopics.RUnlock()
if topic == nil {
log.Warn("writing on a topic that the node did not register on - message dropped",
"topic", sendableData.Topic,
)
continue
}
buffToSend := netMes.createMessageBytes(sendableData.Buff)
if len(buffToSend) == 0 {
continue
}
errPublish := topic.Publish(netMes.ctx, buffToSend)
if errPublish != nil {
log.Trace("error sending data", "error", errPublish)
}
}
}(netMes.outgoingPLB)
return nil
}
func (netMes *networkMessenger) newPeerFound(pid peer.ID, topic string) bool {
netMes.mutPeerTopicNotifiers.RLock()
defer netMes.mutPeerTopicNotifiers.RUnlock()
for _, notifier := range netMes.peerTopicNotifiers {
notifier.NewPeerFound(core.PeerID(pid), topic)
}
return true
}
func (netMes *networkMessenger) createMessageBytes(buff []byte) []byte {
message := &data.TopicMessage{
Version: currentTopicMessageVersion,
Payload: buff,
Timestamp: netMes.syncTimer.CurrentTime().Unix(),
}
buffToSend, errMarshal := netMes.marshalizer.Marshal(message)
if errMarshal != nil {
log.Warn("error sending data", "error", errMarshal)
return nil
}
return buffToSend
}
func (netMes *networkMessenger) createSharder(argsNetMes ArgsNetworkMessenger) error {
args := factory.ArgsSharderFactory{
PeerShardResolver: &unknownPeerShardResolver{},
Pid: netMes.p2pHost.ID(),
P2pConfig: argsNetMes.P2pConfig,
PreferredPeersHolder: netMes.preferredPeersHolder,
NodeOperationMode: argsNetMes.NodeOperationMode,
}
var err error
netMes.sharder, err = factory.NewSharder(args)
return err
}
func (netMes *networkMessenger) createDiscoverer(p2pConfig config.P2PConfig) error {
var err error
args := discoveryFactory.ArgsPeerDiscoverer{
Context: netMes.ctx,
Host: netMes.p2pHost,
Sharder: netMes.sharder,
P2pConfig: p2pConfig,
ConnectionsWatcher: netMes.printConnectionsWatcher,
}
netMes.peerDiscoverer, err = discoveryFactory.NewPeerDiscoverer(args)
return err
}
func (netMes *networkMessenger) createConnectionMonitor(p2pConfig config.P2PConfig) error {
reconnecter, ok := netMes.peerDiscoverer.(p2p.Reconnecter)
if !ok {
return fmt.Errorf("%w when converting peerDiscoverer to reconnecter interface", p2p.ErrWrongTypeAssertion)
}
sharder, ok := netMes.sharder.(connectionMonitor.Sharder)
if !ok {
return fmt.Errorf("%w in networkMessenger.createConnectionMonitor", p2p.ErrWrongTypeAssertions)
}
args := connectionMonitor.ArgsConnectionMonitorSimple{
Reconnecter: reconnecter,
Sharder: sharder,
ThresholdMinConnectedPeers: p2pConfig.Node.ThresholdMinConnectedPeers,
PreferredPeersHolder: netMes.preferredPeersHolder,
ConnectionsWatcher: netMes.printConnectionsWatcher,
}
var err error
netMes.connMonitor, err = connectionMonitor.NewLibp2pConnectionMonitorSimple(args)
if err != nil {
return err
}
cmw := newConnectionMonitorWrapper(
netMes.p2pHost.Network(),
netMes.connMonitor,
&disabled.PeerDenialEvaluator{},
)
netMes.p2pHost.Network().Notify(cmw)
netMes.connMonitorWrapper = cmw
go func() {
for {
cmw.CheckConnectionsBlocking()
select {
case <-time.After(durationCheckConnections):
case <-netMes.ctx.Done():
log.Debug("peer monitoring go routine is stopping...")
return
}
}
}()
return nil
}
func (netMes *networkMessenger) createConnectionsMetric() {
netMes.connectionsMetric = metrics.NewConnections()
netMes.p2pHost.Network().Notify(netMes.connectionsMetric)
}
func (netMes *networkMessenger) printLogs() {
addresses := make([]interface{}, 0)
for i, address := range netMes.p2pHost.Addrs() {
addresses = append(addresses, fmt.Sprintf("addr%d", i))
addresses = append(addresses, address.String()+"/p2p/"+netMes.ID().Pretty())
}
log.Info("listening on addresses", addresses...)
go netMes.printLogsStats()
go netMes.checkExternalLoggers()
}
func (netMes *networkMessenger) printLogsStats() {
for {
select {
case <-netMes.ctx.Done():
log.Debug("closing networkMessenger.printLogsStats go routine")
return
case <-time.After(timeBetweenPeerPrints):
}
conns := netMes.connectionsMetric.ResetNumConnections()
disconns := netMes.connectionsMetric.ResetNumDisconnections()
peersInfo := netMes.GetConnectedPeersInfo()
log.Debug("network connection status",
"known peers", len(netMes.Peers()),
"connected peers", len(netMes.ConnectedPeers()),
"intra shard validators", peersInfo.NumIntraShardValidators,
"intra shard observers", peersInfo.NumIntraShardObservers,
"cross shard validators", peersInfo.NumCrossShardValidators,
"cross shard observers", peersInfo.NumCrossShardObservers,
"full history observers", peersInfo.NumFullHistoryObservers,
"unknown", len(peersInfo.UnknownPeers),
"seeders", len(peersInfo.Seeders),
"current shard", peersInfo.SelfShardID,
"validators histogram", netMes.mapHistogram(peersInfo.NumValidatorsOnShard),
"observers histogram", netMes.mapHistogram(peersInfo.NumObserversOnShard),
"preferred peers histogram", netMes.mapHistogram(peersInfo.NumPreferredPeersOnShard),
)
connsPerSec := conns / uint32(timeBetweenPeerPrints/time.Second)
disconnsPerSec := disconns / uint32(timeBetweenPeerPrints/time.Second)
log.Debug("network connection metrics",
"connections/s", connsPerSec,
"disconnections/s", disconnsPerSec,
"connections", conns,
"disconnections", disconns,
"time", timeBetweenPeerPrints,
)
}
}
func (netMes *networkMessenger) mapHistogram(input map[uint32]int) string {
keys := make([]uint32, 0, len(input))
for shard := range input {
keys = append(keys, shard)
}
sort.Slice(keys, func(i, j int) bool {
return keys[i] < keys[j]
})
vals := make([]string, 0, len(keys))
for _, key := range keys {
var shard string
if key == core.MetachainShardId {
shard = "meta"
} else {
shard = fmt.Sprintf("shard %d", key)
}
vals = append(vals, fmt.Sprintf("%s: %d", shard, input[key]))
}
return strings.Join(vals, ", ")
}
func (netMes *networkMessenger) checkExternalLoggers() {
for {
select {
case <-netMes.ctx.Done():
log.Debug("closing networkMessenger.checkExternalLoggers go routine")
return
case <-time.After(timeBetweenExternalLoggersCheck):
}
setupExternalP2PLoggers()
}
}
// Close closes the host, connections and streams
func (netMes *networkMessenger) Close() error {
log.Debug("closing network messenger's host...")
var err error
errHost := netMes.p2pHost.Close()
if errHost != nil {
err = errHost
log.Warn("networkMessenger.Close",
"component", "host",
"error", err)
}
log.Debug("closing network messenger's print connection watcher...")
errConnWatcher := netMes.printConnectionsWatcher.Close()
if errConnWatcher != nil {
err = errConnWatcher
log.Warn("networkMessenger.Close",
"component", "connectionsWatcher",
"error", err)
}
log.Debug("closing network messenger's outgoing load balancer...")
errOplb := netMes.outgoingPLB.Close()
if errOplb != nil {
err = errOplb
log.Warn("networkMessenger.Close",
"component", "outgoingPLB",
"error", err)
}
log.Debug("closing network messenger's peers on channel...")
errPoc := netMes.poc.Close()
if errPoc != nil {
log.Warn("networkMessenger.Close",
"component", "peersOnChannel",
"error", errPoc)
}
log.Debug("closing network messenger's connection monitor...")
errConnMonitor := netMes.connMonitor.Close()
if errConnMonitor != nil {
log.Warn("networkMessenger.Close",
"component", "connMonitor",
"error", errConnMonitor)
}
log.Debug("closing network messenger's components through the context...")
netMes.cancelFunc()
log.Debug("closing network messenger's debugger...")
errDebugger := netMes.debugger.Close()
if errDebugger != nil {
err = errDebugger
log.Warn("networkMessenger.Close",
"component", "debugger",
"error", err)
}
log.Debug("closing network messenger's peerstore...")
errPeerStore := netMes.p2pHost.Peerstore().Close()
if errPeerStore != nil {
err = errPeerStore
log.Warn("networkMessenger.Close",
"component", "peerstore",
"error", err)
}
if err == nil {
log.Info("network messenger closed successfully")
}
return err
}
// ID returns the messenger's ID
func (netMes *networkMessenger) ID() core.PeerID {
h := netMes.p2pHost
return core.PeerID(h.ID())
}
// Peers returns the list of all known peers ID (including self)
func (netMes *networkMessenger) Peers() []core.PeerID {
peers := make([]core.PeerID, 0)
for _, p := range netMes.p2pHost.Peerstore().Peers() {
peers = append(peers, core.PeerID(p))
}
return peers
}
// Addresses returns all addresses found in peerstore
func (netMes *networkMessenger) Addresses() []string {
addrs := make([]string, 0)
for _, address := range netMes.p2pHost.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 {
return netMes.p2pHost.ConnectToPeer(netMes.ctx, address)
}
// Bootstrap will start the peer discovery mechanism
func (netMes *networkMessenger) Bootstrap() error {
err := netMes.peerDiscoverer.Bootstrap()
if err == nil {
log.Info("started the network discovery process...")
}
return err
}
// WaitForConnections will wait the maxWaitingTime duration or until the target connected peers was achieved
func (netMes *networkMessenger) WaitForConnections(maxWaitingTime time.Duration, minNumOfPeers uint32) {
startTime := time.Now()
defer func() {
log.Debug("networkMessenger.WaitForConnections",
"waited", time.Since(startTime), "num connected peers", len(netMes.ConnectedPeers()))
}()
if minNumOfPeers == 0 {
log.Debug("networkMessenger.WaitForConnections", "waiting", maxWaitingTime)
time.Sleep(maxWaitingTime)
return
}
netMes.waitForConnections(maxWaitingTime, minNumOfPeers)
}
func (netMes *networkMessenger) waitForConnections(maxWaitingTime time.Duration, minNumOfPeers uint32) {
log.Debug("networkMessenger.WaitForConnections", "waiting", maxWaitingTime, "min num of peers", minNumOfPeers)
ctxMaxWaitingTime, cancel := context.WithTimeout(context.Background(), maxWaitingTime)
defer cancel()
for {
if netMes.shouldStopWaiting(ctxMaxWaitingTime, minNumOfPeers) {
return
}
}
}
func (netMes *networkMessenger) shouldStopWaiting(ctxMaxWaitingTime context.Context, minNumOfPeers uint32) bool {
ctx, cancel := context.WithTimeout(context.Background(), pollWaitForConnectionsInterval)
defer cancel()
select {
case <-ctxMaxWaitingTime.Done():
return true
case <-ctx.Done():
return int(minNumOfPeers) <= len(netMes.ConnectedPeers())
}
}
// IsConnected returns true if current node is connected to provided peer
func (netMes *networkMessenger) IsConnected(peerID core.PeerID) bool {
h := netMes.p2pHost
connectedness := h.Network().Connectedness(peer.ID(peerID))
return connectedness == network.Connected
}
// ConnectedPeers returns the current connected peers list
func (netMes *networkMessenger) ConnectedPeers() []core.PeerID {
h := netMes.p2pHost
connectedPeers := make(map[core.PeerID]struct{})
for _, conn := range h.Network().Conns() {
p := core.PeerID(conn.RemotePeer())
if netMes.IsConnected(p) {
connectedPeers[p] = struct{}{}
}
}
peerList := make([]core.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.p2pHost
conns := make([]string, 0)
for _, c := range h.Network().Conns() {
conns = append(conns, c.RemoteMultiaddr().String()+"/p2p/"+c.RemotePeer().Pretty())
}
return conns
}
// PeerAddresses returns the peer's addresses or empty slice if the peer is unknown
func (netMes *networkMessenger) PeerAddresses(pid core.PeerID) []string {
h := netMes.p2pHost
result := make([]string, 0)
// 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()) {
result = append(result, c.RemoteMultiaddr().String())
break
}
}
// check in peerstore (maybe it is known but not connected)
addresses := h.Peerstore().Addrs(peer.ID(pid.Bytes()))
for _, addr := range addresses {
result = append(result, addr.String())
}
return result
}
// ConnectedPeersOnTopic returns the connected peers on a provided topic
func (netMes *networkMessenger) ConnectedPeersOnTopic(topic string) []core.PeerID {
return netMes.poc.ConnectedPeersOnChannel(topic)
}
// ConnectedFullHistoryPeersOnTopic returns the connected peers on a provided topic
func (netMes *networkMessenger) ConnectedFullHistoryPeersOnTopic(topic string) []core.PeerID {
peerList := netMes.ConnectedPeersOnTopic(topic)
fullHistoryList := make([]core.PeerID, 0)
for _, topicPeer := range peerList {
peerInfo := netMes.peerShardResolver.GetPeerInfo(topicPeer)
if peerInfo.PeerSubType == core.FullHistoryObserver {
fullHistoryList = append(fullHistoryList, topicPeer)
}
}
return fullHistoryList
}
// CreateTopic opens a new topic using pubsub infrastructure
func (netMes *networkMessenger) CreateTopic(name string, createChannelForTopic bool) error {
netMes.mutTopics.Lock()
defer netMes.mutTopics.Unlock()
_, found := netMes.topics[name]
if found {
return nil
}
topic, err := netMes.pb.Join(name)
if err != nil {
return fmt.Errorf("%w for topic %s", err, name)
}
netMes.topics[name] = topic
subscrRequest, err := topic.Subscribe()
if err != nil {
return fmt.Errorf("%w for topic %s", err, name)
}
netMes.subscriptions[name] = subscrRequest
if createChannelForTopic {
err = netMes.outgoingPLB.AddChannel(name)
}
// just a dummy func to consume messages received by the newly created topic
go func() {
var errSubscrNext error
for {
_, errSubscrNext = subscrRequest.Next(netMes.ctx)
if errSubscrNext != nil {
log.Debug("closed subscription",
"topic", subscrRequest.Topic(),
"err", errSubscrNext,
)
return
}
}
}()
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
}
// 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 {
err := netMes.checkSendableData(buff)
if err != nil {
return err
}
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
}
func (netMes *networkMessenger) checkSendableData(buff []byte) error {
if len(buff) > maxSendBuffSize {
return fmt.Errorf("%w, to be sent: %d, maximum: %d", p2p.ErrMessageTooLarge, len(buff), maxSendBuffSize)
}
if len(buff) == 0 {
return p2p.ErrEmptyBufferToSend
}
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.Warn("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. The function allows registering multiple handlers
// on a topic. Each handler should be associated with a new identifier on the same topic. Using same identifier on different
// topics is allowed. The order of handler calling on a particular topic is not deterministic.
func (netMes *networkMessenger) RegisterMessageProcessor(topic string, identifier string, handler p2p.MessageProcessor) error {
if check.IfNil(handler) {
return fmt.Errorf("%w when calling networkMessenger.RegisterMessageProcessor for topic %s",
p2p.ErrNilValidator, topic)
}
netMes.mutTopics.Lock()
defer netMes.mutTopics.Unlock()
topicProcs := netMes.processors[topic]
if topicProcs == nil {
topicProcs = newTopicProcessors()
netMes.processors[topic] = topicProcs
err := netMes.registerOnPubSub(topic, topicProcs)
if err != nil {
return err
}
}
err := topicProcs.addTopicProcessor(identifier, handler)
if err != nil {
return fmt.Errorf("%w, topic %s", err, topic)
}
return nil
}
func (netMes *networkMessenger) registerOnPubSub(topic string, topicProcs *topicProcessors) error {
return netMes.pb.RegisterTopicValidator(topic, netMes.pubsubCallback(topicProcs, topic))
}
func (netMes *networkMessenger) pubsubCallback(topicProcs *topicProcessors, topic string) func(ctx context.Context, pid peer.ID, message *pubsub.Message) bool {
return func(ctx context.Context, pid peer.ID, message *pubsub.Message) bool {
fromConnectedPeer := core.PeerID(pid)
msg, err := netMes.transformAndCheckMessage(message, fromConnectedPeer, topic)
if err != nil {
log.Trace("p2p validator - new message", "error", err.Error(), "topic", topic)
return false
}
identifiers, handlers := topicProcs.getList()
messageOk := true
for index, handler := range handlers {
err = handler.ProcessReceivedMessage(msg, fromConnectedPeer)
if err != nil {
log.Trace("p2p validator",
"error", err.Error(),
"topic", topic,
"originator", p2p.MessageOriginatorPid(msg),
"from connected peer", p2p.PeerIdToShortString(fromConnectedPeer),
"seq no", p2p.MessageOriginatorSeq(msg),
"topic identifier", identifiers[index],
)
messageOk = false
}
}
netMes.processDebugMessage(topic, fromConnectedPeer, uint64(len(message.Data)), !messageOk)