Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to watch for the bitcoin transactions over blockchain via nodejs?

I am using this bitcore npm package. https://bitcore.io/api/lib

And i want to monitor all the transactions over the blockchain, and read the input address, output address and amount associated with that transaction.

But i am unable to find the javascript method to invoke to accomplish this. Even i am not able to find a example for this.

I am looking for as short as something like

var someLib = require('some-bitcore-lib')

someLib.on('transaction-found', function(){
   // print everything
   console.log(arguments);
   // do something else;
})

Any help? Where can i find that some-bitcore-lib or how can i create that in nodejs?

like image 659
codeofnode Avatar asked Aug 04 '17 15:08

codeofnode


1 Answers

Using a third-party API, as the accepted answers suggests, will work in the short-term. But if you're looking for a long-term, reliable, not-rate-limited solution; you should run your own bitcoin node. It, of course, depends on your project's requirements.

For a robust solution to the OP's question, I suggest the following:

  • Run a pruned bitcoin node using bitcoind
  • Enable the ZeroMQ interface of bitcoind with the configuration option zmqpubrawtx=tcp://127.0.0.1:3600. This will enable streaming of raw transaction data to your node.js application
  • Use the ZeroMQ node.js module to subscribe to the bitcoind's ZeroMQ interface
  • Use bitcoinjs-lib to decode the raw transaction data

The following node.js example will use zeromq to subscribe to bitcoind's zeromq interface. Then bitcoinjs-lib is used to decode those raw transactions.

var bitcoin = require('bitcoinjs-lib');
var zmq = require('zeromq');
var sock = zmq.socket('sub');
var addr = 'tcp://127.0.0.1:3600';
sock.connect(addr);
sock.subscribe('rawtx');
sock.on('message', function(topic, message) {
    if (topic.toString() === 'rawtx') {
        var rawTx = message.toString('hex');
        var tx = bitcoin.Transaction.fromHex(rawTx);
        var txid = tx.getId();
        tx.ins = tx.ins.map(function(in) {
            in.address = bitcoin.address.fromOutputScript(in.script, bitcoin.networks.bitcoin);
            return in;
        });
        tx.outs = tx.outs.map(function(out) {
            out.address = bitcoin.address.fromOutputScript(out.script, bitcoin.networks.bitcoin);
            return out;
        });
        console.log('received transaction', txid, tx);
    }
});

For more details, please have a look at this guide

like image 82
c.hill Avatar answered Sep 21 '22 05:09

c.hill