randomize the peers that are given out

This commit is contained in:
Feross Aboukhadijeh 2015-05-19 04:32:09 -07:00
parent 9d8c5d6af2
commit 02c92fd2ba
3 changed files with 10 additions and 11 deletions

View File

@ -1,6 +1,7 @@
module.exports = Swarm module.exports = Swarm
var debug = require('debug')('bittorrent-tracker') var debug = require('debug')('bittorrent-tracker')
var randomIterate = require('random-iterate')
// Regard this as the default implementation of an interface that you // Regard this as the default implementation of an interface that you
// need to support when overriding Server.getSwarm() // need to support when overriding Server.getSwarm()
@ -22,7 +23,7 @@ Swarm.prototype.announce = function (params, cb) {
cb(null, { cb(null, {
complete: self.complete, complete: self.complete,
incomplete: self.incomplete, incomplete: self.incomplete,
peers: self._getPeers(params.numwant, params.peer_id) peers: self._getPeers(params.numwant)
}) })
} else { } else {
cb(new Error('invalid event')) cb(new Error('invalid event'))
@ -92,16 +93,13 @@ Swarm.prototype._onAnnounce_update = function (params, peer) {
} }
} }
// TODO: randomize the peers that are given out Swarm.prototype._getPeers = function (numWant) {
Swarm.prototype._getPeers = function (numWant, fromPeerId) {
var peers = [] var peers = []
for (var peerId in this.peers) { var ite = randomIterate(Object.keys(this.peers))
if (peers.length >= numWant) break while (true) {
if (peerId === fromPeerId) continue // skip self var peerId = ite()
if (peers.length >= numWant || peerId == null) return peers
var peer = this.peers[peerId] var peer = this.peers[peerId]
if (!peer) continue // ignore null values if (peer) peers.push(peer)
peers.push(peer)
} }
return peers
} }

View File

@ -30,6 +30,7 @@
"ip": "^0.3.0", "ip": "^0.3.0",
"minimist": "^1.1.1", "minimist": "^1.1.1",
"once": "^1.3.0", "once": "^1.3.0",
"random-iterate": "^1.0.1",
"run-series": "^1.0.2", "run-series": "^1.0.2",
"simple-get": "^1.3.0", "simple-get": "^1.3.0",
"simple-peer": "^5.0.0", "simple-peer": "^5.0.0",

View File

@ -89,7 +89,7 @@ function serverTest (t, serverType, serverFamily) {
}) })
client2.once('peer', function (addr) { client2.once('peer', function (addr) {
t.equal(addr, clientAddr + ':6881') t.ok(addr === clientAddr + ':6881' || addr === clientAddr + ':6882')
client2.stop() client2.stop()
client2.once('update', function (data) { client2.once('update', function (data) {