-
Notifications
You must be signed in to change notification settings - Fork 9
/
libp2p.go
1381 lines (1206 loc) · 41.6 KB
/
libp2p.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 (
"bytes"
"context"
"crypto/ecdsa"
"errors"
"fmt"
"net"
"os"
"runtime"
"strings"
"sync"
"time"
au "github.com/gauss-project/aurorafs"
"github.com/gauss-project/aurorafs/pkg/addressbook"
"github.com/gauss-project/aurorafs/pkg/aurora"
"github.com/gauss-project/aurorafs/pkg/boson"
beecrypto "github.com/gauss-project/aurorafs/pkg/crypto"
"github.com/gauss-project/aurorafs/pkg/logging"
"github.com/gauss-project/aurorafs/pkg/p2p"
"github.com/gauss-project/aurorafs/pkg/p2p/libp2p/internal/blocklist"
"github.com/gauss-project/aurorafs/pkg/p2p/libp2p/internal/breaker"
"github.com/gauss-project/aurorafs/pkg/p2p/libp2p/internal/handshake"
"github.com/gauss-project/aurorafs/pkg/p2p/libp2p/internal/reacher"
"github.com/gauss-project/aurorafs/pkg/p2p/protobuf"
"github.com/gauss-project/aurorafs/pkg/routetab"
"github.com/gauss-project/aurorafs/pkg/routetab/pb"
"github.com/gauss-project/aurorafs/pkg/storage"
"github.com/gauss-project/aurorafs/pkg/topology/bootnode"
"github.com/gauss-project/aurorafs/pkg/topology/lightnode"
"github.com/gauss-project/aurorafs/pkg/tracing"
"github.com/gogf/gf/v2/os/gtimer"
"github.com/hashicorp/go-multierror"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/crypto"
"github.com/libp2p/go-libp2p-core/event"
"github.com/libp2p/go-libp2p-core/host"
"github.com/libp2p/go-libp2p-core/network"
libp2ppeer "github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/peerstore"
"github.com/libp2p/go-libp2p-core/protocol"
nat "github.com/libp2p/go-libp2p-nat"
"github.com/libp2p/go-libp2p-peerstore/pstoremem"
libp2pquic "github.com/libp2p/go-libp2p-quic-transport"
rcmgr "github.com/libp2p/go-libp2p-resource-manager"
lp2pswarm "github.com/libp2p/go-libp2p-swarm"
basichost "github.com/libp2p/go-libp2p/p2p/host/basic"
"github.com/libp2p/go-libp2p/p2p/net/connmgr"
libp2pping "github.com/libp2p/go-libp2p/p2p/protocol/ping"
"github.com/libp2p/go-tcp-transport"
ws "github.com/libp2p/go-ws-transport"
ma "github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multistream"
"go.uber.org/atomic"
)
var (
_ p2p.Service = (*Service)(nil)
_ p2p.DebugService = (*Service)(nil)
)
const (
peerUserAgentTimeout = time.Second
)
type Service struct {
ctx context.Context
host host.Host
natManager basichost.NATManager
natAddrResolver *staticAddressResolver
pingDialer host.Host
libp2pPeerstore peerstore.Peerstore
metrics metrics
networkID uint64
handshakeService *handshake.Service
addressbook addressbook.Putter
peers *peerRegistry
connectionBreaker breaker.Interface
blocklist *blocklist.Blocklist
protocols []p2p.ProtocolSpec
notifier p2p.PickyNotifier
logger logging.Logger
tracer *tracing.Tracer
ready chan struct{}
halt chan struct{}
lightNodes lightnode.LightNodes
bootNodes bootnode.BootNodes
lightNodeLimit int
protocolsmu sync.RWMutex
route routetab.RelayStream
self boson.Address
nodeMode aurora.Model
reacher p2p.Reacher
networkStatus atomic.Int32
}
type Options struct {
PrivateKey *ecdsa.PrivateKey
NATAddr string
EnableWS bool
EnableQUIC bool
NodeMode aurora.Model
LightNodeLimit int
KadBinMaxPeers int
WelcomeMessage string
Transaction []byte
hostFactory func(...libp2p.Option) (host.Host, error)
}
func New(ctx context.Context, signer beecrypto.Signer, networkID uint64, overlay boson.Address, addr string, ab addressbook.Putter, storer storage.StateStorer, lightNodes *lightnode.Container, bootNodes *bootnode.Container, logger logging.Logger, tracer *tracing.Tracer, o Options) (*Service, error) {
hostObj, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("address: %w", err)
}
ip4Addr := "0.0.0.0"
ip6Addr := "::"
if hostObj != "" {
ip := net.ParseIP(hostObj)
if ip4 := ip.To4(); ip4 != nil {
ip4Addr = ip4.String()
ip6Addr = ""
} else if ip6 := ip.To16(); ip6 != nil {
ip6Addr = ip6.String()
ip4Addr = ""
}
}
var listenAddrs []string
if ip4Addr != "" {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip4/%s/tcp/%s", ip4Addr, port))
if o.EnableWS {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip4/%s/tcp/%s/ws", ip4Addr, port))
}
if o.EnableQUIC {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip4/%s/udp/%s/quic", ip4Addr, port))
}
}
if ip6Addr != "" {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip6/%s/tcp/%s", ip6Addr, port))
if o.EnableWS {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip6/%s/tcp/%s/ws", ip6Addr, port))
}
if o.EnableQUIC {
listenAddrs = append(listenAddrs, fmt.Sprintf("/ip6/%s/udp/%s/quic", ip6Addr, port))
}
}
security := libp2p.DefaultSecurity
libp2pPeerstore, err := pstoremem.NewPeerstore()
if err != nil {
return nil, err
}
var natManager basichost.NATManager
opts := []libp2p.Option{
libp2p.ListenAddrStrings(listenAddrs...),
security,
// Use dedicated peerstore instead the global DefaultPeerstore
libp2p.Peerstore(libp2pPeerstore),
libp2p.UserAgent(userAgent()),
}
if o.NATAddr == "" {
opts = append(opts,
libp2p.NATManager(func(n network.Network) basichost.NATManager {
natManager = basichost.NewNATManager(n)
return natManager
}),
)
}
if o.PrivateKey != nil {
opts = append(opts,
libp2p.Identity((*crypto.Secp256k1PrivateKey)(o.PrivateKey)),
)
}
limit := newLimier(o)
manager, err := rcmgr.NewResourceManager(limit)
if err != nil {
return nil, err
}
low := limit.GetSystemLimits().GetConnTotalLimit()
high := low + 200
connManager, err := connmgr.NewConnManager(low, high)
if err != nil {
return nil, err
}
transports := []libp2p.Option{
libp2p.Transport(tcp.NewTCPTransport, tcp.DisableReuseport()),
libp2p.ResourceManager(manager),
libp2p.DisableRelay(),
libp2p.ConnectionManager(connManager),
}
if o.EnableWS {
transports = append(transports, libp2p.Transport(ws.New))
}
if o.EnableQUIC {
transports = append(transports, libp2p.Transport(libp2pquic.NewTransport))
}
opts = append(opts, transports...)
if o.hostFactory == nil {
// Use the default libp2p host creation
o.hostFactory = libp2p.New
}
h, err := o.hostFactory(opts...)
if err != nil {
return nil, err
}
var advertisableAddresser handshake.AdvertisableAddressResolver
var natAddrResolver *staticAddressResolver
if o.NATAddr == "" {
advertisableAddresser = &UpnpAddressResolver{
host: h,
}
} else {
natAddrResolver, err = newStaticAddressResolver(o.NATAddr, net.LookupIP)
if err != nil {
return nil, fmt.Errorf("static nat: %w", err)
}
advertisableAddresser = natAddrResolver
}
if o.LightNodeLimit <= 0 {
o.LightNodeLimit = lightnode.DefaultLightNodeLimit
}
handshakeService, err := handshake.New(signer, advertisableAddresser, overlay, networkID, o.NodeMode, o.WelcomeMessage, h.ID(), logger, lightNodes, o.LightNodeLimit)
if err != nil {
return nil, fmt.Errorf("handshake service: %w", err)
}
// Create a new dialer for libp2p ping protocol. This ensures that the protocol
// uses a different set of keys to do ping. It prevents inconsistencies in peerstore as
// the addresses used are not dialable and hence should be cleaned up. We should create
// this host with the same transports and security options to be able to dial to other
// peers.
pingDialer, err := o.hostFactory(append(transports, security, libp2p.NoListenAddrs)...)
if err != nil {
return nil, err
}
peerRegistry := newPeerRegistry()
s := &Service{
ctx: ctx,
host: h,
natManager: natManager,
natAddrResolver: natAddrResolver,
pingDialer: pingDialer,
handshakeService: handshakeService,
libp2pPeerstore: libp2pPeerstore,
metrics: newMetrics(),
networkID: networkID,
peers: peerRegistry,
addressbook: ab,
blocklist: blocklist.NewBlocklist(storer),
logger: logger,
tracer: tracer,
connectionBreaker: breaker.NewBreaker(breaker.Options{}), // use default options
ready: make(chan struct{}),
halt: make(chan struct{}),
bootNodes: bootNodes,
lightNodes: lightNodes,
lightNodeLimit: o.LightNodeLimit,
}
peerRegistry.setDisconnecter(s)
_ = h.Network().ResourceManager().ViewSystem(func(scope network.ResourceScope) error {
gtimer.AddSingleton(ctx, time.Second, func(ctx context.Context) {
s.metrics.NumConnsOutbound.Set(float64(scope.Stat().NumConnsOutbound))
s.metrics.NumConnsInbound.Set(float64(scope.Stat().NumConnsInbound))
s.metrics.NumStreamsInbound.Set(float64(scope.Stat().NumStreamsInbound))
s.metrics.NumStreamsOutbound.Set(float64(scope.Stat().NumStreamsOutbound))
s.metrics.NumFD.Set(float64(scope.Stat().NumFD))
s.metrics.Memory.Set(float64(scope.Stat().Memory))
// s.logger.Tracef("libp2p view system %v", scope.Stat())
})
return nil
})
// Construct protocols.
id := protocol.ID(p2p.NewAuroraStreamName(handshake.ProtocolName, handshake.ProtocolVersion, handshake.StreamName))
matcher, err := s.protocolSemverMatcher(id)
if err != nil {
return nil, fmt.Errorf("protocol version match %s: %w", id, err)
}
s.host.SetStreamHandlerMatch(id, matcher, s.handleIncoming)
connMetricNotify := newConnMetricNotify(s.metrics)
h.Network().Notify(peerRegistry) // update peer registry on network events
h.Network().Notify(connMetricNotify)
return s, nil
}
func (s *Service) ApplyRoute(self boson.Address, rt routetab.RelayStream, mode aurora.Model) {
s.route = rt
s.self = self
s.nodeMode = mode
}
func (s *Service) handleIncoming(stream network.Stream) {
select {
case <-s.ready:
case <-s.halt:
go func() { _ = stream.Reset() }()
return
case <-s.ctx.Done():
go func() { _ = stream.Reset() }()
return
}
peerID := stream.Conn().RemotePeer()
handshakeStream := NewStream(stream)
i, err := s.handshakeService.Handle(s.ctx, handshakeStream, stream.Conn().RemoteMultiaddr(), peerID)
if err != nil {
s.logger.Debugf("stream handler: handshake: handle %s: %v", peerID, err)
s.logger.Errorf("stream handler: handshake: unable to handshake with peer id %v", peerID)
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(peerID)
return
}
overlay := i.Address.Overlay
blocked, err := s.blocklist.Exists(overlay)
if err != nil {
s.logger.Debugf("stream handler: blocklisting: exists %s: %v", overlay, err)
s.logger.Errorf("stream handler: internal error while connecting with peer %s", overlay)
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(peerID)
return
}
if blocked {
s.logger.Errorf("stream handler: blocked connection from blocklisted peer %s", overlay)
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(peerID)
return
}
if exists := s.peers.addIfNotExists(stream.Conn(), overlay, i.NodeMode); exists {
s.logger.Debugf("stream handler: peer %s already exists", overlay)
if err = handshakeStream.FullClose(); err != nil {
s.logger.Debugf("stream handler: could not close stream %s: %v", overlay, err)
s.logger.Errorf("stream handler: unable to handshake with peer %v", overlay)
_ = s.Disconnect(overlay, "unable to close handshake stream")
}
return
}
if err = handshakeStream.FullClose(); err != nil {
s.logger.Debugf("stream handler: could not close stream %s: %v", overlay, err)
s.logger.Errorf("stream handler: unable to handshake with peer %v", overlay)
_ = s.Disconnect(overlay, "could not fully close stream on handshake")
return
}
if i.NodeMode.IsFull() {
err = s.addressbook.Put(i.Address.Overlay, *i.Address)
if err != nil {
s.logger.Debugf("stream handler: addressbook put error %s: %v", peerID, err)
s.logger.Errorf("stream handler: unable to persist peer %v", peerID)
_ = s.Disconnect(i.Address.Overlay, "unable to persist peer in addressbook")
return
}
}
peer := p2p.Peer{Address: overlay, Mode: i.NodeMode}
s.protocolsmu.RLock()
for _, tn := range s.protocols {
if tn.ConnectIn != nil {
if err := tn.ConnectIn(s.ctx, peer); err != nil {
s.logger.Debugf("stream handler: connectIn: protocol: %s, version:%s, peer: %s: %v", tn.Name, tn.Version, overlay, err)
_ = s.Disconnect(overlay, "failed to process inbound connection notifier")
s.protocolsmu.RUnlock()
return
}
}
}
s.protocolsmu.RUnlock()
if !s.peers.Exists(overlay) {
s.logger.Warningf("stream handler: inbound peer %s does not exist, disconnecting", overlay)
_ = s.Disconnect(overlay, "unknown inbound peer")
return
}
if s.notifier != nil {
if !i.NodeMode.IsFull() && s.lightNodes != nil {
s.lightNodes.Connected(s.ctx, peer)
// light node announces explicitly
if err := s.notifier.Announce(s.ctx, peer.Address, i.NodeMode.IsFull()); err != nil {
s.logger.Debugf("stream handler: notifier.Announce: %s: %v", peer.Address.String(), err)
}
if s.lightNodes.Count() > s.lightNodeLimit {
// kick another node to fit this one in
p, err := s.lightNodes.RandomPeer(peer.Address)
if err != nil {
s.logger.Debugf("stream handler: cant find a peer slot for light node: %v", err)
_ = s.Disconnect(peer.Address, "unable to find peer slot for light node")
return
} else {
s.logger.Tracef("stream handler: kicking away light node %s to make room for %s", p.String(), peer.Address.String())
s.metrics.KickedOutPeersCount.Inc()
_ = s.Disconnect(p, "kicking away light node to make room for peer")
return
}
}
} else {
if i.NodeMode.IsBootNode() && s.bootNodes != nil {
s.bootNodes.Connected(s.ctx, peer)
} else {
if err = s.notifier.Connected(s.ctx, peer, false); err != nil {
s.logger.Debugf("stream handler: notifier.Connected: peer disconnected: %s: %v", i.Address.Overlay, err)
// note: this cannot be unit tested since the node
// waiting on handshakeStream.FullClose() on the other side
// might actually get a stream reset when we disconnect here
// resulting in a flaky response from the Connect method on
// the other side.
// that is why the Pick method has been added to the notifier
// interface, in addition to the possibility of deciding whether
// a peer connection is wanted prior to adding the peer to the
// peer registry and starting the protocols.
_ = s.Disconnect(overlay, fmt.Sprintf("unable to signal connection notifier %s", err))
return
}
// when a full node connects, we gossip about it to the
// light nodes so that they can also have a chance at building
// a solid topology.
_ = s.lightNodes.EachPeer(func(addr boson.Address, _ uint8) (bool, bool, error) {
go func(addressee, peer boson.Address, fullnode bool) {
if err := s.notifier.AnnounceTo(s.ctx, addressee, peer, fullnode); err != nil {
s.logger.Debugf("stream handler: notifier.Announce to light node %s %s: %v", addressee.String(), peer.String(), err)
}
}(addr, peer.Address, i.NodeMode.IsFull())
return false, false, nil
})
}
}
s.notifier.NotifyPeerState(p2p.PeerInfo{
Overlay: peer.Address,
Mode: peer.Mode.Bv.Bytes(),
State: p2p.PeerStateConnectIn,
})
}
s.metrics.HandledStreamCount.Inc()
if s.reacher != nil {
s.reacher.Connected(overlay, i.Address.Underlay)
}
peerUserAgent := appendSpace(s.peerUserAgent(s.ctx, peerID))
s.logger.Debugf("stream handler: successfully connected to peer %s%s%s (inbound)", i.Address.ShortString(), i.LightString(), peerUserAgent)
s.logger.Infof("stream handler: successfully connected to peer %s%s%s (inbound)", i.Address.Overlay, i.LightString(), peerUserAgent)
}
func (s *Service) reachabilityWorker() error {
sub, err := s.host.EventBus().Subscribe([]interface{}{new(event.EvtLocalReachabilityChanged)})
if err != nil {
return fmt.Errorf("failed subscribing to reachability event %w", err)
}
go func() {
defer sub.Close()
for {
select {
case <-s.ctx.Done():
return
case e := <-sub.Out():
if r, ok := e.(event.EvtLocalReachabilityChanged); ok {
select {
case <-s.ready:
case <-s.halt:
return
}
s.logger.Debugf("reachability changed to %s", r.Reachability.String())
s.notifier.UpdateReachability(p2p.ReachabilityStatus(r.Reachability))
}
}
}
}()
return nil
}
func (s *Service) SetPickyNotifier(n p2p.PickyNotifier) {
s.handshakeService.SetPicker(n)
s.reacher = reacher.New(s, n, nil)
s.notifier = n
}
func (s *Service) AddProtocol(p p2p.ProtocolSpec) (err error) {
for _, ss := range p.StreamSpecs {
ss := ss
id := protocol.ID(p2p.NewAuroraStreamName(p.Name, p.Version, ss.Name))
matcher, err := s.protocolSemverMatcher(id)
if err != nil {
return fmt.Errorf("protocol version match %s: %w", id, err)
}
s.host.SetStreamHandlerMatch(id, matcher, func(streamlibp2p network.Stream) {
start := time.Now()
peerID := streamlibp2p.Conn().RemotePeer()
overlay, found := s.peers.overlay(peerID)
if !found {
_ = streamlibp2p.Reset()
s.logger.Debugf("overlay address for peer %q not found", peerID)
return
}
md, found := s.peers.mode(peerID)
if !found {
_ = streamlibp2p.Reset()
s.logger.Debugf("fullnode info for peer %q not found", peerID)
return
}
stream := newStream(streamlibp2p)
// exchange headers
if err := handleHeaders(ss.Headler, stream, overlay); err != nil {
s.logger.Debugf("handle protocol %s/%s: stream %s: peer %s: handle headers: %v", p.Name, p.Version, ss.Name, overlay, err)
_ = stream.Reset()
return
}
s.metrics.HeadersExchangeDuration.Observe(time.Since(start).Seconds())
ctx, cancel := context.WithCancel(s.ctx)
s.peers.addStream(peerID, streamlibp2p, cancel)
defer s.peers.removeStream(peerID, streamlibp2p)
// tracing: get span tracing context and add it to the context
// silently ignore if the peer is not providing tracing
ctx, err := s.tracer.WithContextFromHeaders(ctx, stream.Headers())
if err != nil && !errors.Is(err, tracing.ErrContextNotFound) {
s.logger.Debugf("handle protocol %s/%s: stream %s: peer %s: get tracing context: %v", p.Name, p.Version, ss.Name, overlay, err)
_ = stream.Reset()
return
}
logger := tracing.NewLoggerWithTraceID(ctx, s.logger)
s.metrics.HandledStreamCount.Inc()
if err := ss.Handler(ctx, p2p.Peer{Address: overlay, Mode: md}, stream); err != nil {
var de *p2p.DisconnectError
if errors.As(err, &de) {
logger.Tracef("libp2p handler(%s): disconnecting %s", p.Name, overlay.String())
_ = stream.Reset()
_ = s.Disconnect(overlay, de.Error())
logger.Tracef("handler(%s): disconnecting %s due to disconnect error", p.Name, overlay.String())
}
var bpe *p2p.BlockPeerError
if errors.As(err, &bpe) {
_ = stream.Reset()
if err := s.Blocklist(overlay, bpe.Duration(), bpe.Error()); err != nil {
logger.Debugf("blocklist: could not blocklist peer %s: %v", peerID, err)
logger.Errorf("unable to blocklist peer %v", peerID)
}
logger.Tracef("handler(%s): blocklisted %s", p.Name, overlay.String())
}
// count unexpected requests
if errors.Is(err, p2p.ErrUnexpected) {
s.metrics.UnexpectedProtocolReqCount.Inc()
}
logger.Debugf("could not handle protocol %s/%s: stream %s: peer %s: error: %v", p.Name, p.Version, ss.Name, overlay, err)
return
}
})
}
s.protocolsmu.Lock()
s.protocols = append(s.protocols, p)
s.protocolsmu.Unlock()
return nil
}
func (s *Service) Addresses() (addreses []ma.Multiaddr, err error) {
for _, addr := range s.host.Addrs() {
a, err := buildUnderlayAddress(addr, s.host.ID())
if err != nil {
return nil, err
}
addreses = append(addreses, a)
}
if s.natAddrResolver != nil && len(addreses) > 0 {
a, err := s.natAddrResolver.Resolve(addreses[0])
if err != nil {
return nil, err
}
addreses = append(addreses, a)
}
return addreses, nil
}
func (s *Service) NATAddresses() (addresses []net.Addr, err error) {
maxDepth := 5
// only check nat address nearest the node
var natIterFn func(natInst *nat.NAT, depth int) error
natIterFn = func(natInst *nat.NAT, depth int) error {
if depth == maxDepth {
return nil
}
// if nat is closed, instance will be nil
if natInst == nil {
return nil
}
natMaps := natInst.Mappings()
for _, natMap := range natMaps {
addr, err := natMap.ExternalAddr()
if err != nil {
if errors.Is(err, nat.ErrNoMapping) {
continue
}
return err
}
addresses = append(addresses, addr)
if natMap.NAT() != natInst {
if err := natIterFn(natMap.NAT(), depth+1); err != nil {
return err
}
}
}
return nil
}
if s.natManager != nil {
if err := natIterFn(s.natManager.NAT(), 0); err != nil {
return nil, err
}
} else {
proto := strings.Split(s.natAddrResolver.multiProto, "/")
addr, err := net.ResolveTCPAddr("tcp", proto[len(proto)-1]+":"+s.natAddrResolver.port)
if err != nil {
return nil, err
}
addresses = append(addresses, addr)
}
return addresses, nil
}
func (s *Service) NATManager() basichost.NATManager {
return s.natManager
}
func (s *Service) BlocklistedPeers() ([]p2p.BlockPeers, error) {
return s.blocklist.Peers()
}
func (s *Service) Blocklist(overlay boson.Address, duration time.Duration, reason string) error {
if s.NetworkStatus() != p2p.NetworkStatusAvailable {
return errors.New("blocklisting peer when network not available")
}
s.logger.Tracef("libp2p blocklist: peer %s for %v reason: %s", overlay.String(), duration, reason)
if err := s.blocklist.Add(overlay, duration); err != nil {
s.metrics.BlocklistedPeerErrCount.Inc()
_ = s.Disconnect(overlay, "failed blocklisting peer")
return fmt.Errorf("blocklist peer %s: %v", overlay, err)
}
s.metrics.BlocklistedPeerCount.Inc()
_ = s.Disconnect(overlay, "blocklisting peer")
return nil
}
func (s *Service) BlocklistRemove(overlay boson.Address) error {
return s.blocklist.Remove(overlay)
}
func buildHostAddress(peerID libp2ppeer.ID) (ma.Multiaddr, error) {
return ma.NewMultiaddr(fmt.Sprintf("/p2p/%s", peerID.Pretty()))
}
func buildUnderlayAddress(addr ma.Multiaddr, peerID libp2ppeer.ID) (ma.Multiaddr, error) {
// Build host multiaddress
hostAddr, err := buildHostAddress(peerID)
if err != nil {
return nil, err
}
return addr.Encapsulate(hostAddr), nil
}
func (s *Service) Connect(ctx context.Context, addr ma.Multiaddr) (peer *p2p.Peer, err error) {
defer func() { err = multierror.Append(err, s.determineCurrentNetworkStatus(err)).ErrorOrNil() }()
// Extract the peer ID from the multiaddr.
info, err := libp2ppeer.AddrInfoFromP2pAddr(addr)
if err != nil {
return nil, fmt.Errorf("addr from p2p: %w", err)
}
hostAddr, err := buildHostAddress(info.ID)
if err != nil {
return nil, fmt.Errorf("build host address: %w", err)
}
remoteAddr := addr.Decapsulate(hostAddr)
if peer, found := s.peers.isConnected(info.ID, remoteAddr); found {
return peer, p2p.ErrAlreadyConnected
}
if err := s.connectionBreaker.Execute(func() error { return s.host.Connect(ctx, *info) }); err != nil {
if errors.Is(err, breaker.ErrClosed) {
s.metrics.ConnectBreakerCount.Inc()
return nil, p2p.NewConnectionBackoffError(err, s.connectionBreaker.ClosedUntil())
}
return nil, err
}
stream, err := s.newStreamForPeerID(ctx, info.ID, handshake.ProtocolName, handshake.ProtocolVersion, handshake.StreamName)
if err != nil {
_ = s.host.Network().ClosePeer(info.ID)
return nil, fmt.Errorf("connect new stream: %w", err)
}
handshakeStream := NewStream(stream)
i, err := s.handshakeService.Handshake(ctx, handshakeStream, stream.Conn().RemoteMultiaddr(), stream.Conn().RemotePeer())
if err != nil {
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(info.ID)
return nil, fmt.Errorf("handshake: %w", err)
}
if !i.NodeMode.IsFull() {
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(info.ID)
return nil, p2p.ErrDialLightNode
}
overlay := i.Address.Overlay
blocked, err := s.blocklist.Exists(overlay)
if err != nil {
s.logger.Debugf("blocklisting: exists %s: %v", info.ID, err)
s.logger.Errorf("internal error while connecting with peer %s", info.ID)
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(info.ID)
return nil, err
}
if blocked {
s.logger.Errorf("blocked connection to blocklisted peer %s", info.ID)
_ = handshakeStream.Reset()
_ = s.host.Network().ClosePeer(info.ID)
return nil, p2p.ErrPeerBlocklisted
}
if exists := s.peers.addIfNotExists(stream.Conn(), overlay, i.NodeMode); exists {
if err := handshakeStream.FullClose(); err != nil {
_ = s.Disconnect(overlay, "failed closing handshake stream after connect")
return nil, fmt.Errorf("peer exists, full close: %w", err)
}
return &p2p.Peer{
Address: overlay,
Mode: i.NodeMode,
}, nil
}
if err := handshakeStream.FullClose(); err != nil {
_ = s.Disconnect(overlay, "could not fully close handshake stream after connect")
return nil, fmt.Errorf("connect full close %w", err)
}
if i.NodeMode.IsFull() {
err = s.addressbook.Put(overlay, *i.Address)
if err != nil {
_ = s.Disconnect(overlay, "failed storing peer in addressbook")
return nil, fmt.Errorf("storing boson address: %w", err)
}
}
s.protocolsmu.RLock()
for _, tn := range s.protocols {
if tn.ConnectOut != nil {
if err := tn.ConnectOut(ctx, p2p.Peer{Address: overlay, Mode: i.NodeMode}); err != nil {
s.logger.Debugf("connectOut: protocol: %s, version:%s, peer: %s: %v", tn.Name, tn.Version, overlay, err)
_ = s.Disconnect(overlay, fmt.Sprintf("failed to process outbound connection notifier %s", err))
s.protocolsmu.RUnlock()
return nil, fmt.Errorf("connectOut: protocol: %s, version:%s: %w", tn.Name, tn.Version, err)
}
}
}
s.protocolsmu.RUnlock()
if !s.peers.Exists(overlay) {
_ = s.Disconnect(overlay, "outbound peer does not exist")
return nil, fmt.Errorf("libp2p connect: peer %s does not exist %w", overlay, p2p.ErrPeerNotFound)
}
if i.NodeMode.IsBootNode() {
s.bootNodes.Connected(ctx, p2p.Peer{Address: overlay, Mode: i.NodeMode})
}
s.metrics.CreatedConnectionCount.Inc()
if s.reacher != nil {
s.reacher.Connected(overlay, i.Address.Underlay)
}
peerUserAgent := appendSpace(s.peerUserAgent(ctx, info.ID))
s.logger.Debugf("successfully connected to peer %s%s%s (outbound)", i.Address.ShortString(), i.LightString(), peerUserAgent)
s.logger.Infof("successfully connected to peer %s%s%s (outbound)", overlay, i.LightString(), peerUserAgent)
return &p2p.Peer{
Address: overlay,
Mode: i.NodeMode,
}, nil
}
func (s *Service) Disconnect(overlay boson.Address, reason string) error {
s.metrics.DisconnectCount.Inc()
s.logger.Debugf("libp2p disconnect: disconnecting peer %s reason: %s", overlay, reason)
found, full, peerID := s.peers.remove(overlay)
if !found {
s.logger.Debugf("libp2p disconnect: peer %s not found", overlay)
return p2p.ErrPeerNotFound
}
_ = s.host.Network().ClosePeer(peerID)
peer := p2p.Peer{Address: overlay, Mode: full}
s.protocolsmu.RLock()
for _, tn := range s.protocols {
if tn.DisconnectOut != nil {
if err := tn.DisconnectOut(peer); err != nil {
s.logger.Debugf("disconnectOut: protocol: %s, version:%s, peer: %s: %v", tn.Name, tn.Version, overlay, err)
}
}
}
s.protocolsmu.RUnlock()
if s.notifier != nil {
s.notifier.Disconnected(peer, reason)
}
if s.lightNodes != nil {
s.lightNodes.Disconnected(peer)
}
if s.bootNodes != nil {
s.bootNodes.Disconnected(peer)
}
if s.reacher != nil {
s.reacher.Disconnected(overlay)
}
return nil
}
// disconnected is a registered peer registry event
func (s *Service) disconnected(peer p2p.Peer) {
s.protocolsmu.RLock()
for _, tn := range s.protocols {
if tn.DisconnectIn != nil {
if err := tn.DisconnectIn(peer); err != nil {
s.logger.Debugf("disconnectIn: protocol: %s, version:%s, peer: %s: %v", tn.Name, tn.Version, peer.Address.String(), err)
}
}
}
s.protocolsmu.RUnlock()
if s.notifier != nil {
s.notifier.Disconnected(peer, "libp2p event")
}
if s.lightNodes != nil {
s.lightNodes.Disconnected(peer)
}
if s.bootNodes != nil {
s.bootNodes.Disconnected(peer)
}
if s.reacher != nil {
s.reacher.Disconnected(peer.Address)
}
}
func (s *Service) Peers() []p2p.Peer {
return s.peers.peers()
}
func (s *Service) PeerID(overlay boson.Address) (id libp2ppeer.ID, found bool) {
return s.peers.peerID(overlay)
}
func (s *Service) ResourceManager() network.ResourceManager {
return s.host.Network().ResourceManager()
}
func (s *Service) getProtocolHandler(protocolName, protocolVersion, streamName string) (hand *p2p.StreamSpec, err error) {
id := protocol.ID(p2p.NewAuroraStreamName(protocolName, protocolVersion, streamName))
matcher, err := s.protocolSemverMatcher(id)
if err != nil {
err = fmt.Errorf("protocol version match %s: %w", id, err)
return
}
var spec p2p.StreamSpec
for _, ss := range s.protocols {
if ss.Name == protocolName {
for _, v := range ss.StreamSpecs {
if matcher(p2p.NewAuroraStreamName(protocolName, ss.Version, v.Name)) {
spec = v
break
}
}
break
}
}
if spec.Handler == nil {
err = fmt.Errorf("no handler match %s", id)
return
}
return &spec, nil
}
func (s *Service) CallHandlerWithConnChain(ctx context.Context, last, src p2p.Peer, stream p2p.Stream, protocolName, protocolVersion, streamName string) (err error) {
spec, err := s.getProtocolHandler(protocolName, protocolVersion, streamName)
if err != nil {
return
}
// tracing: get span tracing context and add it to the context
// silently ignore if the peer is not providing tracing
ctx, err = s.tracer.WithContextFromHeaders(ctx, stream.Headers())
if err != nil && !errors.Is(err, tracing.ErrContextNotFound) {
s.logger.Debugf("handle protocol %s/%s: stream %s: peer %s: get tracing context: %v", protocolName, protocolVersion, streamName, src.Address, err)
_ = stream.Reset()
return
}
_, err = stream.Write([]byte("ack"))
if err != nil {
return fmt.Errorf("send ack err %s", err)
}
logger := tracing.NewLoggerWithTraceID(ctx, s.logger)
s.metrics.HandledStreamCount.Inc()
err = spec.Handler(ctx, src, stream)
if err != nil {
var de *p2p.DisconnectError
if errors.As(err, &de) {
logger.Tracef("CallHandlerWithConnChain libp2p handler(%s): disconnecting last %s", streamName, last.Address)
_ = stream.Reset()
_ = s.Disconnect(last.Address, de.Error())
}
// count unexpected requests
if errors.Is(err, p2p.ErrUnexpected) {
s.metrics.UnexpectedProtocolReqCount.Inc()
}
logger.Debugf("could not call handle protocol %s/%s: relay stream %s: peer %s: error: %v", protocolName, protocolVersion, streamName, src.Address, err)
}
return
}
func (s *Service) NewConnChainRelayStream(ctx context.Context, target boson.Address, headers p2p.Headers, protocolName, protocolVersion, streamName string) (p2p.Stream, error) {
next, err := s.route.GetNextHopRandomOrFind(ctx, target)
if err != nil {
return nil, err
}
peerID, found := s.peers.peerID(next)
if !found {
return nil, p2p.ErrPeerNotFound
}
streamlibp2p, err := s.newStreamForPeerID(ctx, peerID, routetab.ProtocolName, routetab.ProtocolVersion, routetab.StreamOnRelayConnChain)
if err != nil {