Browse Source

simplified example for peer discovery, added some debug output to discoverPeers(), made Peer reference the connection created from createConnection()

patch-2
Gordon Hall 11 years ago
parent
commit
e82867007e
  1. 10
      examples/PeerDiscovery.js
  2. 4
      lib/Peer.js
  3. 19
      lib/PeerManager.js

10
examples/PeerDiscovery.js

@ -2,14 +2,10 @@ var PeerManager = require('../lib/PeerManager');
var peerman = new PeerManager();
peerman.discoverPeers(function(err, peers) {
// we get an array of peer instances
console.log(peers);
// the peer manager caches the tried seeds and any results
console.log(peerman.seeds);
// we can use this array of peers to add to the manager
peers.forEach(function(p) {
peerman.addPeer(p);
});
// but let's limit it to 6 connections for this example
var p = 0;
do { peerman.addPeer(peers[p]); p++; } while (p <= 6);
// then we can start the manager
peerman.start();
});

4
lib/Peer.js

@ -34,8 +34,8 @@ function Peer(host, port, services) {
Peer.IPV6_IPV4_PADDING = new Buffer([0,0,0,0,0,0,0,0,0,0,255,255]);
Peer.prototype.createConnection = function () {
var c = Net.createConnection(this.port, this.host);
return c;
this.connection = Net.createConnection(this.port, this.host);
return this.connection;
};
Peer.prototype.getHostAsBuffer = function () {

19
lib/PeerManager.js

@ -26,6 +26,13 @@ function PeerManager(config) {
this.interval = 5000;
this.minConnections = 8;
this.minKnownPeers = 10;
// keep track of tried seeds and results
this.seeds = {
resolved: [],
failed: [],
results: {}
};
}
PeerManager.parent = imports.parent || require('events').EventEmitter;
@ -219,13 +226,6 @@ PeerManager.prototype.discoverPeers = function(callback) {
var networks = imports.networks || require('../networks')[this.config.network];
var seeds = networks.dnsSeeds;
// keep track of tried seeds and results
self.seeds = {
resolved: [],
failed: [],
results: {}
};
var dnsExecutor = seeds.map(function(seed) {
return function(done) {
// have we already resolved this seed?
@ -234,16 +234,19 @@ PeerManager.prototype.discoverPeers = function(callback) {
return done(null, self.seeds.results[seed]);
}
// has this seed failed to resolve?
if (~self.seeds.resolved.indexOf(seed)) {
if (~self.seeds.failed.indexOf(seed)) {
// if so, pass back empty results
return done(null, []);
}
// otherwise resolve the dns seed to get some peers
log.info('resolving dns seed '+ seed);
dns.resolve(seed, function(err, peers) {
if (err) {
log.err('failed to resolve dns seed '+ seed, err);
self.seeds.failed.push(seed);
return done(null, []);
}
log.info('found '+ peers.length + ' peers from ' + seed);
self.seeds.resolved.push(seed);
self.seeds.results[seed] = peers;
return done(null, peers);

Loading…
Cancel
Save