2

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'); });
peer.connect()

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. – Pieter Wuille Nov 14 '16 at 17:14
  • I am connecting to a local node. But this code is separated. – FedFranzoni Nov 14 '16 at 17:34
0

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

peer.on('connected', function(){ console.log('connected'); });

You can just do on ready instead.

peer.on('ready', function(){ console.log('connected'); });

Example connecting to a peer and receiving notifications

var bitcore = require('bitcore-lib');
var Peer = require('bitcore-p2p').Peer;

var peer = new Peer({host: "101.201.31.79"});
//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(){
    console.log("disconnected");
});
//loop through peer notifications
peer.on('inv', function(message){
    var nodeMsg = message.inventory;
    var nodeMsgLen = nodeMsg.length;
    for (var i = 0; i < nodeMsgLen; i++){
        console.log(nodeMsg[i].hash);
    };
});
//connect
peer.connect();
  • 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 – FedFranzoni Nov 15 '16 at 10:14
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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