diff --git a/lib/bcoin/peer.js b/lib/bcoin/peer.js index 9ad848ce..dbf5dad0 100644 --- a/lib/bcoin/peer.js +++ b/lib/bcoin/peer.js @@ -12,14 +12,14 @@ try { } catch (e) { } -function Peer(pool, socket, options) { +function Peer(pool, createSocket, options) { if (!(this instanceof Peer)) return new Peer(pool, socket, options); EventEmitter.call(this); this.pool = pool; - this.socket = socket; + this.socket = null; this.parser = new bcoin.protocol.parser(); this.framer = new bcoin.protocol.framer(); this.chain = this.pool.chain; @@ -29,6 +29,16 @@ function Peer(pool, socket, options) { this.ack = false; this.options = options || {}; + if (this.options.backoff) { + var self = this; + setTimeout(function() { + self.socket = createSocket(); + self.emit('socket'); + }, this.options.backoff); + } else { + this.socket = createSocket(); + } + this._broadcast = { timeout: this.options.broadcastTimeout || 30000, interval: this.options.broadcastInterval || 3000, @@ -47,7 +57,12 @@ function Peer(pool, socket, options) { interval: this.options.pingInterval || 30000 }; - this._init(); + this.setMaxListeners(4000); + + if (this.socket) + this._init(); + else + this.once('socket', this._init); } inherits(Peer, EventEmitter); module.exports = Peer; @@ -85,8 +100,6 @@ Peer.prototype._init = function init() { self.ack = true; self.emit('ack'); }); - - this.setMaxListeners(4000); }; Peer.prototype.broadcast = function broadcast(items) { @@ -150,6 +163,9 @@ Peer.prototype.updateWatch = function updateWatch() { Peer.prototype.destroy = function destroy() { if (this.destroyed) return; + if (!this.socket) + return this.once('socket', this.destroy); + this.destroyed = true; this.socket.destroy(); this.socket = null; @@ -171,8 +187,13 @@ Peer.prototype.destroy = function destroy() { // Private APIs Peer.prototype._write = function write(chunk) { - if (!this.socket) + if (this.destroyed) return; + if (!this.socket) { + return this.once('socket', function() { + this._write(chunk); + }); + } if (NodeBuffer) this.socket.write(new NodeBuffer(chunk)); else diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index d22d2dc8..6996dff8 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -97,8 +97,9 @@ Pool.prototype._addLoader = function _addLoader() { if (this.peers.load !== null) return; - var socket = this.createConnection(); - var peer = bcoin.peer(this, socket, this.options.peer); + var peer = new bcoin.peer(this, this.createConnection, { + backoff: 750 * Math.random() + }); this.peers.load = peer; var self = this; @@ -233,8 +234,9 @@ Pool.prototype._addPeer = function _addPeer() { if (this.peers.block.length + this.peers.pending.length >= this.size) return; - var socket = this.createConnection(); - var peer = bcoin.peer(this, socket, this.options.peer); + var peer = new bcoin.peer(this, this.createConnection, { + backoff: 750 * Math.random() + }); this.peers.pending.push(peer);