From f8a449953bfbdc5da738d197202fae216b36b935 Mon Sep 17 00:00:00 2001 From: Brian Tiger Chow Date: Mon, 8 Dec 2014 18:04:41 -0800 Subject: [PATCH] fix(core) bootstrap panic @jbenet @mappum License: MIT Signed-off-by: Brian Tiger Chow --- core/bootstrap.go | 15 +++++++++++---- core/bootstrap_test.go | 20 ++++++++++++++++++++ util/math2/math2.go | 9 +++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 core/bootstrap_test.go create mode 100644 util/math2/math2.go diff --git a/core/bootstrap.go b/core/bootstrap.go index df1ffa6aa..31da79da0 100644 --- a/core/bootstrap.go +++ b/core/bootstrap.go @@ -11,6 +11,7 @@ import ( inet "github.com/jbenet/go-ipfs/net" peer "github.com/jbenet/go-ipfs/peer" dht "github.com/jbenet/go-ipfs/routing/dht" + math2 "github.com/jbenet/go-ipfs/util/math2" ) const ( @@ -68,10 +69,7 @@ func bootstrap(ctx context.Context, } } - var randomSubset []peer.Peer - for _, val := range rand.Perm(numCxnsToCreate) { - randomSubset = append(randomSubset, notConnected[val]) - } + var randomSubset = randomSubsetOfPeers(notConnected, numCxnsToCreate) if err := connect(ctx, r, randomSubset); err != nil { return err } @@ -119,3 +117,12 @@ func toPeer(ps peer.Peerstore, bootstrap *config.BootstrapPeer) (peer.Peer, erro p.AddAddress(maddr) return p, nil } + +func randomSubsetOfPeers(in []peer.Peer, max int) []peer.Peer { + n := math2.IntMin(max, len(in)) + var out []peer.Peer + for _, val := range rand.Perm(n) { + out = append(out, in[val]) + } + return out +} diff --git a/core/bootstrap_test.go b/core/bootstrap_test.go new file mode 100644 index 000000000..356b65399 --- /dev/null +++ b/core/bootstrap_test.go @@ -0,0 +1,20 @@ +package core + +import ( + "testing" + + peer "github.com/jbenet/go-ipfs/peer" + testutil "github.com/jbenet/go-ipfs/util/testutil" +) + +func TestSubsetWhenMaxIsGreaterThanLengthOfSlice(t *testing.T) { + var ps []peer.Peer + sizeofSlice := 100 + for i := 0; i < sizeofSlice; i++ { + ps = append(ps, testutil.RandPeer()) + } + out := randomSubsetOfPeers(ps, 2*sizeofSlice) + if len(out) != len(ps) { + t.Fail() + } +} diff --git a/util/math2/math2.go b/util/math2/math2.go new file mode 100644 index 000000000..e8a75b5f7 --- /dev/null +++ b/util/math2/math2.go @@ -0,0 +1,9 @@ +package math2 + +// IntMin returns the smaller of x or y. +func IntMin(x, y int) int { + if x < y { + return x + } + return y +}