@@ -2,13 +2,15 @@ package p2p
2
2
3
3
import (
4
4
"context"
5
+ "math/rand"
5
6
"time"
6
7
7
8
dht "github.com/libp2p/go-libp2p-kad-dht"
8
9
pubsub "github.com/libp2p/go-libp2p-pubsub"
9
10
"github.com/libp2p/go-libp2p/core/discovery"
10
11
"github.com/libp2p/go-libp2p/core/host"
11
12
"github.com/libp2p/go-libp2p/core/network"
13
+ "github.com/libp2p/go-libp2p/core/peer"
12
14
"github.com/libp2p/go-libp2p/core/protocol"
13
15
"github.com/libp2p/go-libp2p/p2p/discovery/util"
14
16
"github.com/rs/zerolog/log"
@@ -58,6 +60,8 @@ func dhtRoutingOptions(config *p2pNodeConfig) []dht.Option {
58
60
59
61
if config .IsBootstrapNode {
60
62
opts = append (opts , dht .Mode (dht .ModeServer ))
63
+ } else {
64
+ opts = append (opts , dht .Mode (dht .ModeAutoServer ))
61
65
}
62
66
63
67
return opts
@@ -88,17 +92,21 @@ func findPeers(ctx context.Context, h host.Host, d discovery.Discoverer, ns stri
88
92
newConnections := 0
89
93
failedDials := 0
90
94
ourId := h .ID ().String ()
91
- for _ , p := range peers {
95
+
96
+ randomizedPeers := randomizePeers (peers )
97
+
98
+ for _ , p := range randomizedPeers {
92
99
collectPeerAddresses (p )
93
100
if p .ID == h .ID () {
94
101
continue
95
102
}
96
- metricsP2PPeerConnectedness .WithLabelValues (ourId , p .ID .String ()).Set (float64 (h .Network ().Connectedness (p .ID )))
103
+ connectedness := h .Network ().Connectedness (p .ID )
104
+ metricsP2PPeerConnectedness .WithLabelValues (ourId , p .ID .String ()).Set (float64 (connectedness ))
97
105
peerPing := h .Peerstore ().LatencyEWMA (p .ID )
98
106
if peerPing != 0 {
99
107
metricsP2PPeerPing .WithLabelValues (ourId , p .ID .String ()).Set (peerPing .Seconds ())
100
108
}
101
- if h . Network (). Connectedness ( p . ID ) != network .Connected {
109
+ if connectedness != network .Connected {
102
110
_ , err = h .Network ().DialPeer (ctx , p .ID )
103
111
if err != nil {
104
112
log .Debug ().
@@ -120,3 +128,12 @@ func findPeers(ctx context.Context, h host.Host, d discovery.Discoverer, ns stri
120
128
}
121
129
}
122
130
}
131
+
132
+ func randomizePeers (peers []peer.AddrInfo ) []peer.AddrInfo {
133
+ randomIndexes := rand .Perm (len (peers ))
134
+ randomized := make ([]peer.AddrInfo , len (peers ))
135
+ for _ , index := range randomIndexes {
136
+ randomized = append (randomized , peers [index ])
137
+ }
138
+ return randomized
139
+ }
0 commit comments