fix(core) bootstrap panic
@jbenet @mappum License: MIT Signed-off-by: Brian Tiger Chow <brian@perfmode.com>
Brian Tiger Chow committed
Dec 8, 2014 at 18:04 UTC
f8a449953bfbdc5da738d197202fae216b36b935
3 files changed
+40
-4
core/bootstrap.go
+11
-4
@@ -11,6 +11,7 @@ import (
11
inet "github.com/jbenet/go-ipfs/net"
12
peer "github.com/jbenet/go-ipfs/peer"
13
dht "github.com/jbenet/go-ipfs/routing/dht"
14
+ math2 "github.com/jbenet/go-ipfs/util/math2"
15
)
16
17
const (
@@ -68,10 +69,7 @@ func bootstrap(ctx context.Context,
69
}
70
}
71
71
- var randomSubset []peer.Peer
72
- for _, val := range rand.Perm(numCxnsToCreate) {
73
- randomSubset = append(randomSubset, notConnected[val])
74
- }
72
+ var randomSubset = randomSubsetOfPeers(notConnected, numCxnsToCreate)
73
if err := connect(ctx, r, randomSubset); err != nil {
74
return err
75
}
@@ -119,3 +117,12 @@ func toPeer(ps peer.Peerstore, bootstrap *config.BootstrapPeer) (peer.Peer, erro
117
p.AddAddress(maddr)
118
return p, nil
119
}
120
+
121
+func randomSubsetOfPeers(in []peer.Peer, max int) []peer.Peer {
122
+ n := math2.IntMin(max, len(in))
123
+ var out []peer.Peer
124
+ for _, val := range rand.Perm(n) {
125
+ out = append(out, in[val])
126
+ }
127
+ return out
128
+}
core/bootstrap_test.go
new
+20
@@ -0,0 +1,20 @@
1
+package core
2
+
3
+import (
4
+ "testing"
5
+
6
+ peer "github.com/jbenet/go-ipfs/peer"
7
+ testutil "github.com/jbenet/go-ipfs/util/testutil"
8
+)
9
+
10
+func TestSubsetWhenMaxIsGreaterThanLengthOfSlice(t *testing.T) {
11
+ var ps []peer.Peer
12
+ sizeofSlice := 100
13
+ for i := 0; i < sizeofSlice; i++ {
14
+ ps = append(ps, testutil.RandPeer())
15
+ }
16
+ out := randomSubsetOfPeers(ps, 2*sizeofSlice)
17
+ if len(out) != len(ps) {
18
+ t.Fail()
19
+ }
20
+}
util/math2/math2.go
new
+9
@@ -0,0 +1,9 @@
1
+package math2
2
+
3
+// IntMin returns the smaller of x or y.
4
+func IntMin(x, y int) int {
5
+ if x < y {
6
+ return x
7
+ }
8
+ return y
9
+}