fix(core) bootstrap panic

@jbenet @mappum

License: MIT
Signed-off-by: Brian Tiger Chow <brian@perfmode.com>
This commit is contained in:
Brian Tiger Chow 2014-12-08 18:04:41 -08:00
parent 5f3ae91f9f
commit f8a449953b
3 changed files with 40 additions and 4 deletions

View File

@ -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
}

20
core/bootstrap_test.go Normal file
View File

@ -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()
}
}

9
util/math2/math2.go Normal file
View File

@ -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
}