-
Notifications
You must be signed in to change notification settings - Fork 2
/
kademlia.go
1367 lines (1172 loc) · 36.2 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"
"math"
"math/big"
"math/bits"
"sync"
"time"
"github.com/ethsana/sana/pkg/addressbook"
"github.com/ethsana/sana/pkg/discovery"
"github.com/ethsana/sana/pkg/logging"
"github.com/ethsana/sana/pkg/p2p"
"github.com/ethsana/sana/pkg/shed"
"github.com/ethsana/sana/pkg/swarm"
"github.com/ethsana/sana/pkg/topology"
im "github.com/ethsana/sana/pkg/topology/kademlia/internal/metrics"
"github.com/ethsana/sana/pkg/topology/kademlia/internal/waitnext"
"github.com/ethsana/sana/pkg/topology/pslice"
ma "github.com/multiformats/go-multiaddr"
)
const (
nnLowWatermark = 2 // the number of peers in consecutive deepest bins that constitute as nearest neighbours
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
defaultBitSuffixLength = 3 // the number of bits used to create pseudo addresses for balancing
addPeerBatchSize = 500
peerConnectionAttemptTimeout = 5 * time.Second // Timeout for establishing a new connection with peer.
)
var (
quickSaturationPeers = 4
saturationPeers = 8
overSaturationPeers = 20
bootNodeOverSaturationPeers = 20
shortRetry = 30 * time.Second
timeToRetry = 2 * shortRetry
broadcastBinSize = 4
)
var (
errOverlayMismatch = errors.New("overlay mismatch")
errPruneEntry = errors.New("prune entry")
errEmptyBin = errors.New("empty bin")
)
type (
binSaturationFunc func(bin uint8, peers, connected *pslice.PSlice) (saturated bool, oversaturated bool)
sanctionedPeerFunc func(peer swarm.Address) bool
)
var noopSanctionedPeerFn = func(_ swarm.Address) bool { return false }
// Options for injecting services to Kademlia.
type Options struct {
SaturationFunc binSaturationFunc
Bootnodes []ma.Multiaddr
StandaloneMode bool
BootnodeMode bool
BitSuffixLength int
}
// Kad is the Swarm forwarding kademlia implementation.
type Kad struct {
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
saturationFunc binSaturationFunc // pluggable saturation function
bitSuffixLength int // additional depth of common prefix for bin
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
bootnodes []ma.Multiaddr
depth uint8 // current neighborhood depth
radius 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 logging.Logger // logger
standalone bool // indicates whether the node is working in standalone mode
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
}
// New returns a new Kademlia.
func New(
base swarm.Address,
addressbook addressbook.Interface,
discovery discovery.Driver,
p2p p2p.Service,
metricsDB *shed.DB,
logger logging.Logger,
o Options,
) *Kad {
if o.SaturationFunc == nil {
os := overSaturationPeers
if o.BootnodeMode {
os = bootNodeOverSaturationPeers
}
o.SaturationFunc = binSaturated(os)
}
if o.BitSuffixLength == 0 {
o.BitSuffixLength = defaultBitSuffixLength
}
k := &Kad{
base: base,
discovery: discovery,
addressBook: addressbook,
p2p: p2p,
saturationFunc: o.SaturationFunc,
bitSuffixLength: o.BitSuffixLength,
commonBinPrefixes: make([][]swarm.Address, int(swarm.MaxBins)),
connectedPeers: pslice.New(int(swarm.MaxBins), base),
knownPeers: pslice.New(int(swarm.MaxBins), base),
bootnodes: o.Bootnodes,
manageC: make(chan struct{}, 1),
waitNext: waitnext.New(),
logger: logger,
standalone: o.StandaloneMode,
bootnode: o.BootnodeMode,
collector: im.NewCollector(metricsDB),
quit: make(chan struct{}),
halt: make(chan struct{}),
done: make(chan struct{}),
wg: sync.WaitGroup{},
metrics: newMetrics(),
}
if k.bitSuffixLength > 0 {
k.generateCommonBinPrefixes()
}
return k
}
func (k *Kad) generateCommonBinPrefixes() {
bitCombinationsCount := int(math.Pow(2, float64(k.bitSuffixLength)))
bitSufixes := make([]uint8, bitCombinationsCount)
for i := 0; i < bitCombinationsCount; i++ {
bitSufixes[i] = uint8(i)
}
addr := swarm.MustParseHexAddress(k.base.String())
addrBytes := addr.Bytes()
_ = addrBytes
binPrefixes := k.commonBinPrefixes
// copy base address
for i := range binPrefixes {
binPrefixes[i] = make([]swarm.Address, bitCombinationsCount)
}
for i := range binPrefixes {
for j := range binPrefixes[i] {
pseudoAddrBytes := make([]byte, len(k.base.Bytes()))
copy(pseudoAddrBytes, k.base.Bytes())
binPrefixes[i][j] = swarm.NewAddress(pseudoAddrBytes)
}
}
for i := range binPrefixes {
for j := range binPrefixes[i] {
pseudoAddrBytes := binPrefixes[i][j].Bytes()
// flip first bit for bin
indexByte, posBit := i/8, i%8
if hasBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)) {
pseudoAddrBytes[indexByte] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)))
} else {
pseudoAddrBytes[indexByte] = bits.Reverse8(setBit(bits.Reverse8(pseudoAddrBytes[indexByte]), uint8(posBit)))
}
// set pseudo suffix
bitSuffixPos := k.bitSuffixLength - 1
for l := i + 1; l < i+k.bitSuffixLength+1; l++ {
index, pos := l/8, l%8
if hasBit(bitSufixes[j], uint8(bitSuffixPos)) {
pseudoAddrBytes[index] = bits.Reverse8(setBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
} else {
pseudoAddrBytes[index] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
}
bitSuffixPos--
}
// clear rest of the bits
for l := i + k.bitSuffixLength + 1; l < len(pseudoAddrBytes)*8; l++ {
index, pos := l/8, l%8
pseudoAddrBytes[index] = bits.Reverse8(clearBit(bits.Reverse8(pseudoAddrBytes[index]), uint8(pos)))
}
}
}
}
// Clears the bit at pos in n.
func clearBit(n, pos uint8) uint8 {
mask := ^(uint8(1) << pos)
return n & mask
}
// Sets the bit at pos in the integer n.
func setBit(n, pos uint8) uint8 {
return n | 1<<pos
}
func hasBit(n, pos uint8) bool {
return n&(1<<pos) > 0
}
// peerConnInfo groups necessary fields needed to create a connection.
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
}
for i := range k.commonBinPrefixes {
if i >= int(k.NeighborhoodDepth()) {
continue
}
for j := range k.commonBinPrefixes[i] {
pseudoAddr := k.commonBinPrefixes[i][j]
closestConnectedPeer, err := closestPeer(k.connectedPeers, pseudoAddr, noopSanctionedPeerFn)
if err != nil {
if errors.Is(err, topology.ErrNotFound) {
break
}
k.logger.Errorf("closest connected peer: %v", err)
continue
}
closestConnectedPO := swarm.ExtendedProximity(closestConnectedPeer.Bytes(), pseudoAddr.Bytes())
if int(closestConnectedPO) >= i+k.bitSuffixLength+1 {
continue
}
// Connect to closest known peer which we haven't tried connecting to recently.
closestKnownPeer, err := closestPeer(k.knownPeers, pseudoAddr, skipPeers)
if err != nil {
if errors.Is(err, topology.ErrNotFound) {
break
}
k.logger.Errorf("closest known peer: %v", err)
continue
}
if k.connectedPeers.Exists(closestKnownPeer) {
continue
}
closestKnownPeerPO := swarm.ExtendedProximity(closestKnownPeer.Bytes(), pseudoAddr.Bytes())
if int(closestKnownPeerPO) < i+k.bitSuffixLength+1 {
continue
}
select {
case <-k.quit:
return
default:
wg.Add(1)
peerConnChan <- &peerConnInfo{
po: swarm.Proximity(k.base.Bytes(), closestKnownPeer.Bytes()),
addr: closestKnownPeer,
}
}
break
}
}
}
// connectNeighbours attempts to connect to the neighbours
// which were not considered by the connectBalanced method.
func (k *Kad) connectNeighbours(wg *sync.WaitGroup, peerConnChan, peerConnChan2 chan<- *peerConnInfo) {
const multiplePeerThreshold = 8
sent := 0
_ = k.knownPeers.EachBinRev(func(addr swarm.Address, po uint8) (bool, bool, error) {
depth := k.NeighborhoodDepth()
if depth > po || po >= depth+multiplePeerThreshold {
return false, true, nil
}
if len(k.connectedPeers.BinPeers(po)) >= overSaturationPeers-1 {
return false, true, nil
}
if k.connectedPeers.Exists(addr) {
return false, false, nil
}
if k.waitNext.Waiting(addr) {
k.metrics.TotalBeforeExpireWaits.Inc()
return false, false, nil
}
select {
case <-k.quit:
return true, false, nil
default:
wg.Add(1)
peerConnChan <- &peerConnInfo{
po: po,
addr: addr,
}
sent++
}
// We want to sent number of attempts equal to saturationPeers
// in order to speed up the topology build.
next := sent == saturationPeers
if next {
sent = 0
}
return false, next, nil
})
_ = k.knownPeers.EachBinRev(func(addr swarm.Address, po uint8) (bool, bool, error) {
depth := k.NeighborhoodDepth()
if po < depth+multiplePeerThreshold {
return false, true, nil
}
if k.connectedPeers.Exists(addr) {
return false, false, nil
}
if k.waitNext.Waiting(addr) {
k.metrics.TotalBeforeExpireWaits.Inc()
return false, false, nil
}
select {
case <-k.quit:
return true, false, nil
default:
wg.Add(1)
peerConnChan2 <- &peerConnInfo{
po: po,
addr: addr,
}
}
// The bin could be saturated or not, so a decision cannot
// be made before checking the next peer, so we iterate to next.
return false, true, 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, peerConnChan, peerConnChan2 <-chan *peerConnInfo) {
connect := func(peer *peerConnInfo) {
bzzAddr, err := k.addressBook.Get(peer.addr)
switch {
case errors.Is(err, addressbook.ErrNotFound):
k.logger.Debugf("kademlia: empty address book entry for peer %q", peer.addr)
k.knownPeers.Remove(peer.addr)
return
case err != nil:
k.logger.Debugf("kademlia: failed to get address book entry for peer %q: %v", peer.addr, 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.Debugf("kademlia: could not remove peer %q from addressbook", peer.addr)
}
}
switch err = k.connect(ctx, peer.addr, bzzAddr.Underlay); {
case errors.Is(err, errPruneEntry):
k.logger.Debugf("kademlia: dial to light node with overlay %q and underlay %q", peer.addr, bzzAddr.Underlay)
remove(peer)
return
case errors.Is(err, errOverlayMismatch):
k.logger.Debugf("kademlia: overlay mismatch has occurred to an overlay %q with underlay %q", peer.addr, bzzAddr.Underlay)
remove(peer)
return
case err != nil:
k.logger.Debugf("kademlia: peer not reachable from kademlia %q: %v", bzzAddr, err)
k.logger.Warningf("peer not reachable when attempting to connect")
return
}
k.waitNext.Set(peer.addr, time.Now().Add(shortRetry), 0)
k.connectedPeers.Add(peer.addr)
k.metrics.TotalOutboundConnections.Inc()
k.collector.Record(peer.addr, im.PeerLogIn(time.Now(), im.PeerConnectionDirectionOutbound))
k.depthMu.Lock()
k.depth = recalcDepth(k.connectedPeers, k.radius)
k.depthMu.Unlock()
k.logger.Debugf("kademlia: connected to peer: %q in bin: %d", peer.addr, 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 < 64; i++ {
go connAttempt(peerConnChan)
}
for i := 0; i < 8; i++ {
go connAttempt(peerConnChan2)
}
}
// 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() {
defer k.wg.Done()
defer close(k.done)
defer k.logger.Debugf("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
peerConnChan := make(chan *peerConnInfo)
peerConnChan2 := make(chan *peerConnInfo)
go k.connectionAttemptsHandler(ctx, &wg, peerConnChan, peerConnChan2)
for {
select {
case <-k.quit:
return
case <-time.After(15 * time.Second):
start := time.Now()
if err := k.collector.Flush(); err != nil {
k.metrics.InternalMetricsFlushTotalErrors.Inc()
k.logger.Debugf("kademlia: unable to flush metrics counters to the persistent store: %v", err)
} else {
k.metrics.InternalMetricsFlushTime.Observe(float64(time.Since(start).Nanoseconds()))
}
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.standalone {
continue
}
oldDepth := k.NeighborhoodDepth()
k.connectNeighbours(&wg, peerConnChan, peerConnChan2)
k.connectBalanced(&wg, peerConnChan2)
wg.Wait()
k.depthMu.Lock()
depth := k.depth
radius := k.radius
k.depthMu.Unlock()
k.logger.Tracef(
"kademlia: connector took %s to finish: old depth %d; new depth %d",
time.Since(start),
oldDepth,
depth,
)
k.metrics.CurrentDepth.Set(float64(depth))
k.metrics.CurrentRadius.Set(float64(radius))
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)
}
}
}
}
func (k *Kad) Start(_ context.Context) error {
k.wg.Add(1)
go k.manage()
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.Errorf("addressbook overlays: %w", err)
return
}
k.AddPeers(addresses...)
k.metrics.StartAddAddressBookOverlaysTime.Observe(float64(time.Since(start).Nanoseconds()))
}()
// trigger the first manage loop immediately so that
// we can start connecting to the bootnode quickly
k.notifyManageLoop()
return nil
}
func (k *Kad) connectBootNodes(ctx context.Context) {
var attempts, connected int
totalAttempts := maxBootNodeAttempts * len(k.bootnodes)
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
for _, addr := range k.bootnodes {
if attempts >= totalAttempts || connected >= 3 {
return
}
if _, err := p2p.Discover(ctx, addr, func(addr ma.Multiaddr) (stop bool, err error) {
k.logger.Tracef("connecting to bootnode %s", 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.Debugf("connect fail %s: %v", addr, err)
k.logger.Warningf("connect to bootnode %s", addr)
return false, err
}
k.logger.Debugf("connect to bootnode fail: %v", err)
return false, nil
}
if err := k.connected(ctx, bzzAddress.Overlay); err != nil {
return false, err
}
k.logger.Tracef("connected to bootnode %s", addr)
connected++
// connect to max 3 bootnodes
return connected >= 3, nil
}); err != nil && !errors.Is(err, context.Canceled) {
k.logger.Debugf("discover fail %s: %v", addr, err)
k.logger.Warningf("discover to bootnode %s", 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) binSaturationFunc {
return func(bin uint8, peers, connected *pslice.PSlice) (bool, bool) {
potentialDepth := recalcDepth(peers, swarm.MaxPO)
// short circuit for bins which are >= depth
if bin >= potentialDepth {
return false, false
}
// lets assume for now that the minimum number of peers in a bin
// would be 2, under which we would always want to connect to new peers
// obviously this should be replaced with a better optimization
// the iterator is used here since when we check if a bin is saturated,
// the plain number of size of bin might not suffice (for example for squared
// gaps measurement)
size := 0
_ = connected.EachBin(func(_ swarm.Address, po uint8) (bool, bool, error) {
if po == bin {
size++
}
return false, false, nil
})
return size >= saturationPeers, size >= oversaturationAmount
}
}
// recalcDepth calculates and returns the kademlia depth.
func recalcDepth(peers *pslice.PSlice, radius uint8) uint8 {
// handle edge case separately
if peers.Length() <= nnLowWatermark {
return 0
}
var (
peersCtr = uint(0)
candidate = uint8(0)
shallowestEmpty, noEmptyBins = peers.ShallowestEmpty()
)
shallowestUnsaturated := uint8(0)
binCount := 0
_ = peers.EachBinRev(func(_ swarm.Address, bin uint8) (bool, bool, error) {
if bin == shallowestUnsaturated {
binCount++
return false, false, nil
}
if bin > shallowestUnsaturated && binCount < quickSaturationPeers {
// this means we have less than quickSaturation 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
})
// 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 < shallowestUnsaturated {
shallowestUnsaturated = shallowestEmpty
}
_ = peers.EachBin(func(_ swarm.Address, po uint8) (bool, bool, error) {
peersCtr++
if peersCtr >= nnLowWatermark {
candidate = po
return true, false, nil
}
return false, false, nil
})
if shallowestUnsaturated > candidate {
if radius < candidate {
return radius
}
return candidate
}
if radius < shallowestUnsaturated {
return radius
}
return shallowestUnsaturated
}
// 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.Infof("attempting to connect to peer %q", 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.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 err != nil:
k.logger.Debugf("could not connect to peer %q: %v", peer, err)
retryTime := time.Now().Add(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())
k.collector.Inspect(peer, func(ss *im.Snapshot) {
quickPrune := ss == nil || ss.HasAtMaxOneConnectionAttempt()
if (k.connectedPeers.Length() > 0 && quickPrune) || failedAttempts >= maxConnAttempts {
k.waitNext.Remove(peer)
k.knownPeers.Remove(peer)
if err := k.addressBook.Remove(peer); err != nil {
k.logger.Debugf("could not remove peer from addressbook: %q", peer)
}
k.logger.Debugf("kademlia pruned peer from address book %q", peer)
} else {
k.waitNext.Set(peer, retryTime, failedAttempts)
}
})
return err
case !i.Overlay.Equal(peer):
_ = k.p2p.Disconnect(peer)
_ = k.p2p.Disconnect(i.Overlay)
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
for bin := uint8(0); bin < swarm.MaxBins; bin++ {
connectedPeers, err := randomSubset(k.connectedPeers.BinPeers(bin), broadcastBinSize)
if err != nil {
return err
}
for _, connectedPeer := range connectedPeers {
if connectedPeer.Equal(peer) {
continue
}
addrs = append(addrs, connectedPeer)
if !fullnode {
// we continue here so we dont gossip
// about lightnodes to others.
continue
}
go func(connectedPeer swarm.Address) {
if err := k.discovery.BroadcastPeers(ctx, connectedPeer, peer); err != nil {
k.logger.Debugf("could not gossip peer %s to peer %s: %v", peer, connectedPeer, err)
}
}(connectedPeer)
}
}
if len(addrs) == 0 {
return nil
}
err := k.discovery.BroadcastPeers(ctx, peer, addrs...)
if err != nil {
k.logger.Errorf("kademlia: could not broadcast to peer %s", peer)
_ = k.p2p.Disconnect(peer)
}
return err
}
// AddPeers adds peers to the knownPeers list.
// This does not guarantee that a connection will immediately
// be made to the peer.
func (k *Kad) AddPeers(addrs ...swarm.Address) {
k.knownPeers.Add(addrs...)
k.notifyManageLoop()
}
func (k *Kad) Pick(peer p2p.Peer) bool {
k.metrics.PickCalls.Inc()
if k.bootnode {
// shortcircuit for bootnode mode - always accept connections,
// at least until we find a better solution.
return true
}
po := swarm.Proximity(k.base.Bytes(), peer.Address.Bytes())
_, oversaturated := k.saturationFunc(po, k.knownPeers, k.connectedPeers)
// pick the peer if we are not oversaturated
if !oversaturated {
return true
}
k.metrics.PickCallsFalse.Inc()
return false
}
// Connected is called when a peer has dialed in.
// If forceConnection is true `overSaturated` is ignored for non-bootnodes.
func (k *Kad) Connected(ctx context.Context, peer p2p.Peer, forceConnection bool) error {
address := peer.Address
po := swarm.Proximity(k.base.Bytes(), address.Bytes())
if _, overSaturated := k.saturationFunc(po, k.knownPeers, k.connectedPeers); overSaturated {
if k.bootnode {
randPeer, err := k.randomPeer(po)
if err != nil {
return err
}
_ = k.p2p.Disconnect(randPeer)
return k.connected(ctx, address)
}
if !forceConnection {
return topology.ErrOversaturated
}
}
return k.connected(ctx, address)
}
func (k *Kad) connected(ctx context.Context, addr swarm.Address) error {
if err := k.Announce(ctx, addr, true); err != nil {
return err
}
k.knownPeers.Add(addr)
k.connectedPeers.Add(addr)
k.metrics.TotalInboundConnections.Inc()
k.collector.Record(addr, im.PeerLogIn(time.Now(), im.PeerConnectionDirectionInbound))
k.waitNext.Remove(addr)
k.depthMu.Lock()
k.depth = recalcDepth(k.connectedPeers, k.radius)
k.depthMu.Unlock()
k.notifyManageLoop()
k.notifyPeerSig()
return nil
}
// Disconnected is called when peer disconnects.
func (k *Kad) Disconnected(peer p2p.Peer) {
k.logger.Debugf("kademlia: disconnected peer %s", peer.Address)
k.connectedPeers.Remove(peer.Address)
k.waitNext.SetTryAfter(peer.Address, time.Now().Add(timeToRetry))
k.metrics.TotalInboundDisconnections.Inc()
k.collector.Record(peer.Address, im.PeerLogOut(time.Now()))
k.depthMu.Lock()
k.depth = recalcDepth(k.connectedPeers, k.radius)
k.depthMu.Unlock()
k.notifyManageLoop()
k.notifyPeerSig()
}
func (k *Kad) notifyPeerSig() {
k.peerSigMtx.Lock()
defer k.peerSigMtx.Unlock()
for _, c := range k.peerSig {
// Every peerSig channel has a buffer capacity of 1,
// so every receiver will get the signal even if the
// select statement has the default case to avoid blocking.
select {
case c <- struct{}{}:
default:
}
}
}
func closestPeer(peers *pslice.PSlice, addr swarm.Address, spf sanctionedPeerFunc) (swarm.Address, error) {
closest := swarm.ZeroAddress
err := peers.EachBinRev(func(peer swarm.Address, po uint8) (bool, bool, error) {
// check whether peer is sanctioned
if spf(peer) {
return false, false, nil
}
if closest.IsZero() {
closest = peer
return false, false, nil
}
dcmp, err := swarm.DistanceCmp(addr.Bytes(), closest.Bytes(), peer.Bytes())
if err != nil {
return false, false, err
}
switch dcmp {
case 0:
// do nothing
case -1:
// current peer is closer
closest = peer
case 1:
// closest is already closer to chunk
// do nothing
}
return false, false, nil
})
if err != nil {
return swarm.ZeroAddress, err
}
// check if found
if closest.IsZero() {
return swarm.ZeroAddress, topology.ErrNotFound
}
return closest, nil
}
func isIn(a swarm.Address, addresses []p2p.Peer) bool {
for _, v := range addresses {
if v.Address.Equal(a) {
return true
}
}