I'm trying to run a simple script to connect to a Bitcoin peer, like this one:

  var bitcore = require('bitcore-lib')
  var p2p = require('bitcore-p2p')
  var Peer = p2p.Peer;
  var peer = new Peer({host: 'localhost', port: 18333, network: Networks.testnet})
  peer.on('connect', function () { console.log('connect'); })
  peer.on('ready', function(){  console.log('ready'); });
  peer.on('disconnect', function() {  console.log('connection closed'); });

However, the connection seems to never be established. I only get the 'connect' and the 'connection closed' output, but not 'connected'. The port I set is the one in the Bitcore config file.

Can someone please help me figure out what is the problem?

  • It sounds like you're connecting to yourself. Commented Nov 14, 2016 at 17:14
  • I am connecting to a local node. But this code is separated.
    – FedFranz
    Commented Nov 14, 2016 at 17:34

2 Answers 2


I'm actually not sure how, but now everything works.

I'm writing here a few things to be kept in mind to make it work:

1) the port number is that of the bitcoind server (8333 for mainnet, 18333 for testnet)

2) in case of testnet, the network must be passed as an option to the Peer constructor

3) node version must be 4.x (use nvm use 4), otherwise the code will raise an exception


I'm not sure what exactly you are trying to do with:

peer.on('connected', function(){ 

You can just do on ready instead.

peer.on('ready', function(){

Example connecting to a peer and receiving notifications

var bitcore = require('bitcore-lib');
var Peer = require('bitcore-p2p').Peer;
var peer = new Peer({host: ""});
//IP of one of the btc.com's miners
peer.on('ready', function(){
    console.log("Connected "+peer.version, 
    peer.subversion, peer.bestHeight);
peer.on('disconnect', function(){
//loop through peer notifications
peer.on('inv', function(message){
    var nodeMsg = message.inventory;
    var nodeMsgLen = nodeMsg.length;
    for (var i = 0; i < nodeMsgLen; i++){
  • I had already tried with every event. Maybe the 'ready' event is more approriate (I will update my question). The problem is that it disconnect as soon as it tried to connect. Furthermore, the same code works for livenet. I did a little debug and found out that, in the testnet case, it sends a wrong (I guess) message to the peer, where the 'network' object is set to livenet instead of testnet. I am updating the issue I opened on github. Hope the developers will help
    – FedFranz
    Commented Nov 15, 2016 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.