-
Notifications
You must be signed in to change notification settings - Fork 337
/
kademlia.go
1599 lines (1345 loc) · 44 KB
/
kademlia.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
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package kademlia
import (
"context"
random "crypto/rand"
"encoding/json"
"errors"
"fmt"
"math/big"
"math/rand"
"path/filepath"
"sync"
"time"
"github.com/ethersphere/bee/pkg/addressbook"
"github.com/ethersphere/bee/pkg/discovery"
"github.com/ethersphere/bee/pkg/log"
"github.com/ethersphere/bee/pkg/p2p"
"github.com/ethersphere/bee/pkg/shed"
"github.com/ethersphere/bee/pkg/swarm"
"github.com/ethersphere/bee/pkg/topology"
im "github.com/ethersphere/bee/pkg/topology/kademlia/internal/metrics"
"github.com/ethersphere/bee/pkg/topology/kademlia/internal/waitnext"
"github.com/ethersphere/bee/pkg/topology/pslice"
ma "github.com/multiformats/go-multiaddr"
"golang.org/x/sync/errgroup"
)
// loggerName is the tree path name of the logger for this package.
const loggerName = "kademlia"
const (
maxConnAttempts = 1 // when there is maxConnAttempts failed connect calls for a given peer it is considered non-connectable
maxBootNodeAttempts = 3 // how many attempts to dial to boot-nodes before giving up
maxNeighborAttempts = 3 // how many attempts to dial to boot-nodes before giving up
addPeerBatchSize = 500
// To avoid context.Timeout errors during network failure, the value of
// the peerConnectionAttemptTimeout constant must be equal to or greater
// than 5 seconds (empirically verified).
peerConnectionAttemptTimeout = 15 * time.Second // timeout for establishing a new connection with peer.
)
// Default option values
const (
defaultBitSuffixLength = 4 // the number of bits used to create pseudo addresses for balancing, 2^4, 16 addresses
defaultLowWaterMark = 3 // the number of peers in consecutive deepest bins that constitute as nearest neighbours
defaultSaturationPeers = 8
defaultOverSaturationPeers = 20
defaultBootNodeOverSaturationPeers = 20
defaultShortRetry = 30 * time.Second
defaultTimeToRetry = 2 * defaultShortRetry
defaultBroadcastBinSize = 4
)
var (
errOverlayMismatch = errors.New("overlay mismatch")
errPruneEntry = errors.New("prune entry")
errEmptyBin = errors.New("empty bin")
errAnnounceLightNode = errors.New("announcing light node")
)
type (
binSaturationFunc func(bin uint8, peers, connected *pslice.PSlice, filter peerFilterFunc) bool
sanctionedPeerFunc func(peer swarm.Address) bool
pruneFunc func(depth uint8)
staticPeerFunc func(peer swarm.Address) bool
peerFilterFunc func(peer swarm.Address) bool
filtersFunc func(...im.FilterOp) peerFilterFunc
)
var noopSanctionedPeerFn = func(_ swarm.Address) bool { return false }
// Options for injecting services to Kademlia.
type Options struct {
SaturationFunc binSaturationFunc
Bootnodes []ma.Multiaddr
BootnodeMode bool
PruneFunc pruneFunc
StaticNodes []swarm.Address
FilterFunc filtersFunc
DataDir string
BitSuffixLength *int
TimeToRetry *time.Duration
ShortRetry *time.Duration
SaturationPeers *int
OverSaturationPeers *int
BootnodeOverSaturationPeers *int
BroadcastBinSize *int
LowWaterMark *int
}
// kadOptions are made from Options with default values set
type kadOptions struct {
SaturationFunc binSaturationFunc
Bootnodes []ma.Multiaddr
BootnodeMode bool
PruneFunc pruneFunc
StaticNodes []swarm.Address
FilterFunc filtersFunc
TimeToRetry time.Duration
ShortRetry time.Duration
BitSuffixLength int // additional depth of common prefix for bin
SaturationPeers int
OverSaturationPeers int
BootnodeOverSaturationPeers int
BroadcastBinSize int
LowWaterMark int
}
func newKadOptions(o Options) kadOptions {
ko := kadOptions{
// copy values
SaturationFunc: o.SaturationFunc,
Bootnodes: o.Bootnodes,
BootnodeMode: o.BootnodeMode,
PruneFunc: o.PruneFunc,
StaticNodes: o.StaticNodes,
FilterFunc: o.FilterFunc,
// copy or use default
TimeToRetry: defaultValDuration(o.TimeToRetry, defaultTimeToRetry),
ShortRetry: defaultValDuration(o.ShortRetry, defaultShortRetry),
BitSuffixLength: defaultValInt(o.BitSuffixLength, defaultBitSuffixLength),
SaturationPeers: defaultValInt(o.SaturationPeers, defaultSaturationPeers),
OverSaturationPeers: defaultValInt(o.OverSaturationPeers, defaultOverSaturationPeers),
BootnodeOverSaturationPeers: defaultValInt(o.BootnodeOverSaturationPeers, defaultBootNodeOverSaturationPeers),
BroadcastBinSize: defaultValInt(o.BroadcastBinSize, defaultBroadcastBinSize),
LowWaterMark: defaultValInt(o.LowWaterMark, defaultLowWaterMark),
}
if ko.SaturationFunc == nil {
ko.SaturationFunc = makeSaturationFunc(ko)
}
return ko
}
func defaultValInt(v *int, d int) int {
if v == nil {
return d
}
return *v
}
func defaultValDuration(v *time.Duration, d time.Duration) time.Duration {
if v == nil {
return d
}
return *v
}
func makeSaturationFunc(o kadOptions) binSaturationFunc {
os := o.OverSaturationPeers
if o.BootnodeMode {
os = o.BootnodeOverSaturationPeers
}
return binSaturated(os, isStaticPeer(o.StaticNodes))
}
// Kad is the Swarm forwarding kademlia implementation.
type Kad struct {
opt kadOptions
base swarm.Address // this node's overlay address
discovery discovery.Driver // the discovery driver
addressBook addressbook.Interface // address book to get underlays
p2p p2p.Service // p2p service to connect to nodes with
commonBinPrefixes [][]swarm.Address // list of address prefixes for each bin
connectedPeers *pslice.PSlice // a slice of peers sorted and indexed by po, indexes kept in `bins`
knownPeers *pslice.PSlice // both are po aware slice of addresses
depth uint8 // current neighborhood depth
storageRadius uint8 // storage area of responsibility
depthMu sync.RWMutex // protect depth changes
manageC chan struct{} // trigger the manage forever loop to connect to new peers
peerSig []chan struct{}
peerSigMtx sync.Mutex
logger log.Logger // logger
bootnode bool // indicates whether the node is working in bootnode mode
collector *im.Collector
quit chan struct{} // quit channel
halt chan struct{} // halt channel
done chan struct{} // signal that `manage` has quit
wg sync.WaitGroup
waitNext *waitnext.WaitNext
metrics metrics
staticPeer staticPeerFunc
bgBroadcastCtx context.Context
bgBroadcastCancel context.CancelFunc
reachability p2p.ReachabilityStatus
}
// New returns a new Kademlia.
func New(
base swarm.Address,
addressbook addressbook.Interface,
discovery discovery.Driver,
p2pSvc p2p.Service,
logger log.Logger,
o Options,
) (*Kad, error) {
var k *Kad
if o.DataDir == "" {
logger.Warning("using in-mem store for kademlia metrics, no state will be persisted")
} else {
o.DataDir = filepath.Join(o.DataDir, "kademlia-metrics")
}
sdb, err := shed.NewDB(o.DataDir, nil)
if err != nil {
return nil, fmt.Errorf("unable to create metrics storage: %w", err)
}
imc, err := im.NewCollector(sdb)
if err != nil {
return nil, fmt.Errorf("unable to create metrics collector: %w", err)
}
opt := newKadOptions(o)
k = &Kad{
opt: opt,
base: base,
discovery: discovery,
addressBook: addressbook,
p2p: p2pSvc,
commonBinPrefixes: make([][]swarm.Address, int(swarm.MaxBins)),
connectedPeers: pslice.New(int(swarm.MaxBins), base),
knownPeers: pslice.New(int(swarm.MaxBins), base),
manageC: make(chan struct{}, 1),
waitNext: waitnext.New(),
logger: logger.WithName(loggerName).Register(),
bootnode: opt.BootnodeMode,
collector: imc,
quit: make(chan struct{}),
halt: make(chan struct{}),
done: make(chan struct{}),
metrics: newMetrics(),
staticPeer: isStaticPeer(opt.StaticNodes),
storageRadius: swarm.MaxPO,
}
if k.opt.PruneFunc == nil {
k.opt.PruneFunc = k.pruneOversaturatedBins
}
if k.opt.FilterFunc == nil {
k.opt.FilterFunc = func(f ...im.FilterOp) peerFilterFunc {
return func(peer swarm.Address) bool {
return k.collector.Filter(peer, f...)
}
}
}
if k.opt.BitSuffixLength > 0 {
k.commonBinPrefixes = generateCommonBinPrefixes(k.base, k.opt.BitSuffixLength)
}
k.bgBroadcastCtx, k.bgBroadcastCancel = context.WithCancel(context.Background())
k.metrics.ReachabilityStatus.WithLabelValues(p2p.ReachabilityStatusUnknown.String()).Set(0)
return k, nil
}
type peerConnInfo struct {
po uint8
addr swarm.Address
}
// connectBalanced attempts to connect to the balanced peers first.
func (k *Kad) connectBalanced(wg *sync.WaitGroup, peerConnChan chan<- *peerConnInfo) {
skipPeers := func(peer swarm.Address) bool {
if k.waitNext.Waiting(peer) {
k.metrics.TotalBeforeExpireWaits.Inc()
return true
}
return false
}
depth := k.neighborhoodDepth()
for i := range k.commonBinPrefixes {
binPeersLength := k.knownPeers.BinSize(uint8(i))
// balancer should skip on bins where neighborhood connector would connect to peers anyway
// and there are not enough peers in known addresses to properly balance the bin
if i >= int(depth) && binPeersLength < len(k.commonBinPrefixes[i]) {
continue
}
binPeers := k.knownPeers.BinPeers(uint8(i))
binConnectedPeers := k.connectedPeers.BinPeers(uint8(i))
for j := range k.commonBinPrefixes[i] {
pseudoAddr := k.commonBinPrefixes[i][j]
// Connect to closest known peer which we haven't tried connecting to recently.
_, exists := nClosePeerInSlice(binConnectedPeers, pseudoAddr, noopSanctionedPeerFn, uint8(i+k.opt.BitSuffixLength+1))
if exists {
continue
}
closestKnownPeer, exists := nClosePeerInSlice(binPeers, pseudoAddr, skipPeers, uint8(i+k.opt.BitSuffixLength+1))
if !exists {
continue
}
if k.connectedPeers.Exists(closestKnownPeer) {
continue
}
blocklisted, err := k.p2p.Blocklisted(closestKnownPeer)
if err != nil {
k.logger.Warning("peer blocklist check failed", "error", err)
}
if blocklisted {
continue
}
wg.Add(1)
select {
case peerConnChan <- &peerConnInfo{
po: swarm.Proximity(k.base.Bytes(), closestKnownPeer.Bytes()),
addr: closestKnownPeer,
}:
case <-k.quit:
wg.Done()
return
}
}
}
}
// connectNeighbours attempts to connect to the neighbours
// which were not considered by the connectBalanced method.
func (k *Kad) connectNeighbours(wg *sync.WaitGroup, peerConnChan chan<- *peerConnInfo) {
sent := 0
var currentPo uint8 = 0
_ = k.knownPeers.EachBinRev(func(addr swarm.Address, po uint8) (bool, bool, error) {
// out of depth, skip bin
if po < k.neighborhoodDepth() {
return false, true, nil
}
if po != currentPo {
currentPo = po
sent = 0
}
if k.connectedPeers.Exists(addr) {
return false, false, nil
}
blocklisted, err := k.p2p.Blocklisted(addr)
if err != nil {
k.logger.Warning("peer blocklist check failed", "error", err)
}
if blocklisted {
return false, false, nil
}
if k.waitNext.Waiting(addr) {
k.metrics.TotalBeforeExpireWaits.Inc()
return false, false, nil
}
wg.Add(1)
select {
case peerConnChan <- &peerConnInfo{po: po, addr: addr}:
case <-k.quit:
wg.Done()
return true, false, nil
}
sent++
// We want 'sent' equal to 'saturationPeers'
// in order to skip to the next bin and speed up the topology build.
return false, sent == k.opt.SaturationPeers, nil
})
}
// connectionAttemptsHandler handles the connection attempts
// to peers sent by the producers to the peerConnChan.
func (k *Kad) connectionAttemptsHandler(ctx context.Context, wg *sync.WaitGroup, neighbourhoodChan, balanceChan <-chan *peerConnInfo) {
connect := func(peer *peerConnInfo) {
bzzAddr, err := k.addressBook.Get(peer.addr)
switch {
case errors.Is(err, addressbook.ErrNotFound):
k.logger.Debug("empty address book entry for peer", "peer_address", peer.addr)
k.knownPeers.Remove(peer.addr)
return
case err != nil:
k.logger.Debug("failed to get address book entry for peer", "peer_address", peer.addr, "error", err)
return
}
remove := func(peer *peerConnInfo) {
k.waitNext.Remove(peer.addr)
k.knownPeers.Remove(peer.addr)
if err := k.addressBook.Remove(peer.addr); err != nil {
k.logger.Debug("could not remove peer from addressbook", "peer_address", peer.addr)
}
}
switch err = k.connect(ctx, peer.addr, bzzAddr.Underlay); {
case errors.Is(err, p2p.ErrNetworkUnavailable):
k.logger.Debug("network unavailable when reaching peer", "peer_overlay_address", peer.addr, "peer_underlay_address", bzzAddr.Underlay)
return
case errors.Is(err, errPruneEntry):
k.logger.Debug("dial to light node", "peer_overlay_address", peer.addr, "peer_underlay_address", bzzAddr.Underlay)
remove(peer)
return
case errors.Is(err, errOverlayMismatch):
k.logger.Debug("overlay mismatch has occurred", "peer_overlay_address", peer.addr, "peer_underlay_address", bzzAddr.Underlay)
remove(peer)
return
case errors.Is(err, p2p.ErrPeerBlocklisted):
k.logger.Debug("peer still in blocklist", "peer_address", bzzAddr)
k.logger.Warning("peer still in blocklist")
return
case err != nil:
k.logger.Debug("peer not reachable from kademlia", "peer_address", bzzAddr, "error", err)
k.logger.Warning("peer not reachable when attempting to connect")
return
}
k.waitNext.Set(peer.addr, time.Now().Add(k.opt.ShortRetry), 0)
k.connectedPeers.Add(peer.addr)
k.metrics.TotalOutboundConnections.Inc()
k.collector.Record(peer.addr, im.PeerLogIn(time.Now(), im.PeerConnectionDirectionOutbound))
k.recalcDepth()
k.logger.Info("connected to peer", "peer_address", peer.addr, "proximity_order", peer.po)
k.notifyManageLoop()
k.notifyPeerSig()
}
var (
// The inProgress helps to avoid making a connection
// to a peer who has the connection already in progress.
inProgress = make(map[string]bool)
inProgressMu sync.Mutex
)
connAttempt := func(peerConnChan <-chan *peerConnInfo) {
for {
select {
case <-k.quit:
return
case peer := <-peerConnChan:
addr := peer.addr.String()
if k.waitNext.Waiting(peer.addr) {
k.metrics.TotalBeforeExpireWaits.Inc()
wg.Done()
continue
}
inProgressMu.Lock()
if !inProgress[addr] {
inProgress[addr] = true
inProgressMu.Unlock()
connect(peer)
inProgressMu.Lock()
delete(inProgress, addr)
}
inProgressMu.Unlock()
wg.Done()
}
}
}
for i := 0; i < 32; i++ {
go connAttempt(balanceChan)
}
for i := 0; i < 32; i++ {
go connAttempt(neighbourhoodChan)
}
}
// notifyManageLoop notifies kademlia manage loop.
func (k *Kad) notifyManageLoop() {
select {
case k.manageC <- struct{}{}:
default:
}
}
// manage is a forever loop that manages the connection to new peers
// once they get added or once others leave.
func (k *Kad) manage() {
loggerV1 := k.logger.V(1).Register()
defer k.wg.Done()
defer close(k.done)
defer k.logger.Debug("kademlia manage loop exited")
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-k.quit
cancel()
}()
// The wg makes sure that we wait for all the connection attempts,
// spun up by goroutines, to finish before we try the boot-nodes.
var wg sync.WaitGroup
neighbourhoodChan := make(chan *peerConnInfo)
balanceChan := make(chan *peerConnInfo)
go k.connectionAttemptsHandler(ctx, &wg, neighbourhoodChan, balanceChan)
k.wg.Add(1)
go func() {
defer k.wg.Done()
for {
select {
case <-k.halt:
return
case <-k.quit:
return
case <-time.After(5 * time.Minute):
start := time.Now()
loggerV1.Debug("starting to flush metrics", "start_time", start)
if err := k.collector.Flush(); err != nil {
k.metrics.InternalMetricsFlushTotalErrors.Inc()
k.logger.Debug("unable to flush metrics counters to the persistent store", "error", err)
} else {
k.metrics.InternalMetricsFlushTime.Observe(time.Since(start).Seconds())
loggerV1.Debug("flush metrics done", "elapsed", time.Since(start))
}
}
}
}()
// tell each neighbor about other neighbors periodically
k.wg.Add(1)
go func() {
defer k.wg.Done()
for {
select {
case <-k.halt:
return
case <-k.quit:
return
case <-time.After(5 * time.Minute):
var neighbors []swarm.Address
_ = k.connectedPeers.EachBin(func(addr swarm.Address, bin uint8) (stop bool, jumpToNext bool, err error) {
if bin < k.neighborhoodDepth() {
return true, false, nil
}
neighbors = append(neighbors, addr)
return false, false, nil
})
for i, peer := range neighbors {
if err := k.discovery.BroadcastPeers(ctx, peer, append(neighbors[:i], neighbors[i+1:]...)...); err != nil {
k.logger.Debug("broadcast neighborhood failure", "peer_address", peer, "error", err)
}
}
}
}
}()
for {
select {
case <-k.quit:
return
case <-time.After(15 * time.Second):
k.notifyManageLoop()
case <-k.manageC:
start := time.Now()
select {
case <-k.halt:
// halt stops dial-outs while shutting down
return
case <-k.quit:
return
default:
}
if k.bootnode {
depth := k.neighborhoodDepth()
k.metrics.CurrentDepth.Set(float64(depth))
k.metrics.CurrentlyKnownPeers.Set(float64(k.knownPeers.Length()))
k.metrics.CurrentlyConnectedPeers.Set(float64(k.connectedPeers.Length()))
continue
}
oldDepth := k.neighborhoodDepth()
k.connectBalanced(&wg, balanceChan)
k.connectNeighbours(&wg, neighbourhoodChan)
wg.Wait()
depth := k.neighborhoodDepth()
k.opt.PruneFunc(depth)
loggerV1.Debug("connector finished", "elapsed", time.Since(start), "old_depth", oldDepth, "new_depth", depth)
k.metrics.CurrentDepth.Set(float64(depth))
k.metrics.CurrentlyKnownPeers.Set(float64(k.knownPeers.Length()))
k.metrics.CurrentlyConnectedPeers.Set(float64(k.connectedPeers.Length()))
if k.connectedPeers.Length() == 0 {
select {
case <-k.halt:
continue
default:
}
k.logger.Debug("kademlia: no connected peers, trying bootnodes")
k.connectBootNodes(ctx)
} else {
rs := make(map[string]float64)
ss := k.collector.Snapshot(time.Now())
if err := k.connectedPeers.EachBin(func(addr swarm.Address, _ uint8) (bool, bool, error) {
if ss, ok := ss[addr.ByteString()]; ok {
rs[ss.Reachability.String()]++
}
return false, false, nil
}); err != nil {
k.logger.Error(err, "unable to set peers reachability status")
}
for status, count := range rs {
k.metrics.PeersReachabilityStatus.WithLabelValues(status).Set(count)
}
}
}
}
}
// pruneOversaturatedBins disconnects out of depth peers from oversaturated bins
// while maintaining the balance of the bin and favoring healthy and reachable peers.
func (k *Kad) pruneOversaturatedBins(depth uint8) {
for i := range k.commonBinPrefixes {
if i >= int(depth) {
return
}
binPeersCount := k.connectedPeers.BinSize(uint8(i))
if binPeersCount <= k.opt.OverSaturationPeers {
continue
}
for j := 0; j < len(k.commonBinPrefixes[i]) && k.connectedPeers.BinSize(uint8(i)) > k.opt.OverSaturationPeers; j++ {
binPeers := k.connectedPeers.BinPeers(uint8(i))
peers := k.balancedSlotPeers(k.commonBinPrefixes[i][j], binPeers, i)
if len(peers) <= 1 {
continue
}
var disconnectPeer = swarm.ZeroAddress
var unreachablePeer = swarm.ZeroAddress
for _, peer := range peers {
if ss := k.collector.Inspect(peer); ss != nil {
if !ss.Healthy {
disconnectPeer = peer
break
}
if ss.Reachability != p2p.ReachabilityStatusPublic {
unreachablePeer = peer
}
}
}
if disconnectPeer.IsZero() {
if unreachablePeer.IsZero() {
disconnectPeer = peers[rand.Intn(len(peers))]
} else {
disconnectPeer = unreachablePeer // pick unrechable peer
}
}
err := k.p2p.Disconnect(disconnectPeer, "pruned from oversaturated bin")
if err != nil {
k.logger.Debug("prune disconnect failed", "error", err)
}
}
k.logger.Debug("pruning", "bin", i, "oldBinSize", binPeersCount, "newBinSize", k.connectedPeers.BinSize(uint8(i)))
}
}
func (k *Kad) balancedSlotPeers(pseudoAddr swarm.Address, peers []swarm.Address, po int) []swarm.Address {
var ret []swarm.Address
for _, peer := range peers {
peerPo := swarm.ExtendedProximity(peer.Bytes(), pseudoAddr.Bytes())
if int(peerPo) >= po+k.opt.BitSuffixLength+1 {
ret = append(ret, peer)
}
}
return ret
}
func (k *Kad) Start(_ context.Context) error {
k.wg.Add(1)
go k.manage()
k.AddPeers(k.previouslyConnected()...)
go func() {
select {
case <-k.halt:
return
case <-k.quit:
return
default:
}
var (
start = time.Now()
addresses []swarm.Address
)
err := k.addressBook.IterateOverlays(func(addr swarm.Address) (stop bool, err error) {
addresses = append(addresses, addr)
if len(addresses) == addPeerBatchSize {
k.AddPeers(addresses...)
addresses = nil
}
return false, nil
})
if err != nil {
k.logger.Error(err, "addressbook iterate overlays failed")
return
}
k.AddPeers(addresses...)
k.metrics.StartAddAddressBookOverlaysTime.Observe(time.Since(start).Seconds())
}()
// trigger the first manage loop immediately so that
// we can start connecting to the bootnode quickly
k.notifyManageLoop()
return nil
}
func (k *Kad) previouslyConnected() []swarm.Address {
loggerV1 := k.logger.V(1).Register()
now := time.Now()
ss := k.collector.Snapshot(now)
loggerV1.Debug("metrics snapshot taken", "elapsed", time.Since(now))
var peers []swarm.Address
for addr, p := range ss {
if p.ConnectionTotalDuration > 0 {
peers = append(peers, swarm.NewAddress([]byte(addr)))
}
}
return peers
}
func (k *Kad) connectBootNodes(ctx context.Context) {
loggerV1 := k.logger.V(1).Register()
var attempts, connected int
totalAttempts := maxBootNodeAttempts * len(k.opt.Bootnodes)
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
for _, addr := range k.opt.Bootnodes {
if attempts >= totalAttempts || connected >= 3 {
return
}
if _, err := p2p.Discover(ctx, addr, func(addr ma.Multiaddr) (stop bool, err error) {
loggerV1.Debug("connecting to bootnode", "bootnode_address", addr)
if attempts >= maxBootNodeAttempts {
return true, nil
}
bzzAddress, err := k.p2p.Connect(ctx, addr)
attempts++
k.metrics.TotalBootNodesConnectionAttempts.Inc()
if err != nil {
if !errors.Is(err, p2p.ErrAlreadyConnected) {
k.logger.Debug("connect to bootnode failed", "bootnode_address", addr, "error", err)
k.logger.Warning("connect to bootnode failed", "bootnode_address", addr)
return false, err
}
k.logger.Debug("connect to bootnode failed", "bootnode_address", addr, "error", err)
return false, nil
}
if err := k.onConnected(ctx, bzzAddress.Overlay); err != nil {
return false, err
}
k.metrics.TotalOutboundConnections.Inc()
k.collector.Record(bzzAddress.Overlay, im.PeerLogIn(time.Now(), im.PeerConnectionDirectionOutbound))
loggerV1.Debug("connected to bootnode", "bootnode_address", addr)
connected++
// connect to max 3 bootnodes
return connected >= 3, nil
}); err != nil && !errors.Is(err, context.Canceled) {
k.logger.Debug("discover to bootnode failed", "bootnode_address", addr, "error", err)
k.logger.Warning("discover to bootnode failed", "bootnode_address", addr)
return
}
}
}
// binSaturated indicates whether a certain bin is saturated or not.
// when a bin is not saturated it means we would like to proactively
// initiate connections to other peers in the bin.
func binSaturated(oversaturationAmount int, staticNode staticPeerFunc) binSaturationFunc {
return func(bin uint8, peers, connected *pslice.PSlice, filter peerFilterFunc) bool {
size := 0
_ = connected.EachBin(func(addr swarm.Address, po uint8) (bool, bool, error) {
if po == bin && !filter(addr) && !staticNode(addr) {
size++
}
return false, false, nil
})
return size >= oversaturationAmount
}
}
// recalcDepth calculates, assigns the new depth, and returns if depth has changed
func (k *Kad) recalcDepth() {
k.depthMu.Lock()
defer k.depthMu.Unlock()
var (
peers = k.connectedPeers
filter = k.opt.FilterFunc(im.Reachability(false))
binCount = 0
shallowestUnsaturated = uint8(0)
depth uint8
)
// handle edge case separately
if peers.Length() <= k.opt.LowWaterMark {
k.depth = 0
return
}
_ = peers.EachBinRev(func(addr swarm.Address, bin uint8) (bool, bool, error) {
if filter(addr) {
return false, false, nil
}
if bin == shallowestUnsaturated {
binCount++
return false, false, nil
}
if bin > shallowestUnsaturated && binCount < k.opt.SaturationPeers {
// this means we have less than quickSaturationPeers in the previous bin
// therefore we can return assuming that bin is the unsaturated one.
return true, false, nil
}
shallowestUnsaturated = bin
binCount = 1
return false, false, nil
})
depth = shallowestUnsaturated
shallowestEmpty, noEmptyBins := peers.ShallowestEmpty()
// if there are some empty bins and the shallowestEmpty is
// smaller than the shallowestUnsaturated then set shallowest
// unsaturated to the empty bin.
if !noEmptyBins && shallowestEmpty < depth {
depth = shallowestEmpty
}
var (
peersCtr = uint(0)
candidate = uint8(0)
)
_ = peers.EachBin(func(addr swarm.Address, po uint8) (bool, bool, error) {
if filter(addr) {
return false, false, nil
}
peersCtr++
if peersCtr >= uint(k.opt.LowWaterMark) {
candidate = po
return true, false, nil
}
return false, false, nil
})
if depth > candidate {
depth = candidate
}
k.depth = depth
}
// connect connects to a peer and gossips its address to our connected peers,
// as well as sends the peers we are connected to to the newly connected peer
func (k *Kad) connect(ctx context.Context, peer swarm.Address, ma ma.Multiaddr) error {
k.logger.Debug("attempting connect to peer", "peer_address", peer)
ctx, cancel := context.WithTimeout(ctx, peerConnectionAttemptTimeout)
defer cancel()
k.metrics.TotalOutboundConnectionAttempts.Inc()
switch i, err := k.p2p.Connect(ctx, ma); {
case errors.Is(err, p2p.ErrNetworkUnavailable):
return err
case k.p2p.NetworkStatus() == p2p.NetworkStatusUnavailable:
return p2p.ErrNetworkUnavailable
case errors.Is(err, p2p.ErrDialLightNode):
return errPruneEntry
case errors.Is(err, p2p.ErrAlreadyConnected):
if !i.Overlay.Equal(peer) {
return errOverlayMismatch
}
return nil
case errors.Is(err, context.Canceled):
return err
case errors.Is(err, p2p.ErrPeerBlocklisted):
return err
case err != nil:
k.logger.Debug("could not connect to peer", "peer_address", peer, "error", err)
retryTime := time.Now().Add(k.opt.TimeToRetry)
var e *p2p.ConnectionBackoffError
failedAttempts := 0
if errors.As(err, &e) {
retryTime = e.TryAfter()
} else {
failedAttempts = k.waitNext.Attempts(peer)
failedAttempts++
}
k.metrics.TotalOutboundConnectionFailedAttempts.Inc()
k.collector.Record(peer, im.IncSessionConnectionRetry())
maxAttempts := maxConnAttempts
if swarm.Proximity(k.base.Bytes(), peer.Bytes()) >= k.neighborhoodDepth() {
maxAttempts = maxNeighborAttempts
}
if failedAttempts >= maxAttempts {
k.waitNext.Remove(peer)
k.knownPeers.Remove(peer)
if err := k.addressBook.Remove(peer); err != nil {
k.logger.Debug("could not remove peer from addressbook", "peer_address", peer)
}
k.logger.Debug("peer pruned from address book", "peer_address", peer)
} else {
k.waitNext.Set(peer, retryTime, failedAttempts)
}
return err
case !i.Overlay.Equal(peer):
_ = k.p2p.Disconnect(peer, errOverlayMismatch.Error())
_ = k.p2p.Disconnect(i.Overlay, errOverlayMismatch.Error())
return errOverlayMismatch
}
return k.Announce(ctx, peer, true)
}
// Announce a newly connected peer to our connected peers, but also
// notify the peer about our already connected peers
func (k *Kad) Announce(ctx context.Context, peer swarm.Address, fullnode bool) error {
var addrs []swarm.Address
depth := k.neighborhoodDepth()
isNeighbor := swarm.Proximity(peer.Bytes(), k.base.Bytes()) >= depth
outer:
for bin := uint8(0); bin < swarm.MaxBins; bin++ {
var (
connectedPeers []swarm.Address
err error
)
if bin >= depth && isNeighbor {
connectedPeers = k.binPeers(bin, false) // broadcast all neighborhood peers