How to watch for the bitcoin transactions over blockchain via nodejs? - node.js

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?

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

If you don't have your own node you can use blockchain.info APIs as described in here (https://github.com/blockchain/api-v1-client-node/tree/master/Socket)
const Socket = require('blockchain.info/Socket');
const mySocket = new Socket();
mySocket.onTransaction(function() {
console.log(arguments);
});
You can always watch transactions by running your own node without the need to depend on a service like blockchain.info... For example, if you are using btcd (Golang) (https://github.com/btcsuite/btcd) then you can get notified on transactions like in here (http://godoc.org/github.com/btcsuite/btcrpcclient#Client.NotifyNewTransactions)

I think this is what you're looking for. The tutorial helps the user set up a local btc node and demonstrates how to use a zmq subscription along with RPC comms to accomplish sending and receiving transactions as well as notifications and other functionality.
#c.hill's response is correct but leaves out the more complicated functionality described here :)

Related

How to connect to RouterOS via Nodejs WebSocket?

I'm learning websocket nodejs, I want to connect to routeros via websocket like the https://github.com/aluisiora/node-routeros/ package, the package is too broad, I just want to know how to connect.
I've read the official documentation https://wiki.mikrotik.com/wiki/Manual:API, but I'm having trouble understanding it.
I have tried it this way, but did not get any response:
client.connect(port, host, function () {
console.log("Connected");
client.write(encodeString("/login"));
client.write(encodeString(`=name=${user}`));
client.write(encodeString(`=password=${password}`));
});
client.on("data", function (data) {
console.log("Received: " + data); // not excetue
});
I'm looking for code samples to connect to routeros via nodejs socket, hopefully someone shares here.
Thanks in advance, I really appreciate any answer.
Take into consideration the next things:
RouterOS API has it's own protocol, it has a bit of complexity. The official wiki tell us how to interact with it at LOW LEVEL. For these reason it's very difficult to understand. Isn't for a High Level programmer. Don't worry, We have all been through here.
Routeros v7 have a REST API, that will make the job easier, the exchange language is HTTP protocol, easy right? Actually is at beta stage.
RouterOS Wiki have other package for node.js that seems more easy: Mikronode
solution
Install mikronode package
$ npm install mikronode
use it:
var api = require('mikronode');
var connection = new api('192.168.0.1','admin','password');
connection.connect(function(conn) {
var chan=conn.openChannel();
chan.write('/ip/address/print',function() {
chan.on('done',function(data) {
var parsed = api.parseItems(data);
parsed.forEach(function(item) {
console.log('Interface/IP: '+item.interface+"/"+item.address);
});
chan.close();
conn.close();
});
});
});

How send message on websocket server to specific user( s)

I'm reading up on websockets and after reading a lot of tutorials and blogs (mostly about creating a simple chat application) there is still 1 question unanswered :
Type of technology used aside (node.js or php of python) I find no way of sending a message to 1 user or a group of users without first getting an event of the client to the websocket server ( often called onconnect() or onmessage() ).
Is it then not possible to have some external application or event call some script (bash or php) that uses the existing running websocket instance to send/broadcast some information (text) to one or more connected browsers (websocket clients) ??
Sorry if this is a stupid question but I am not able to find an answer by reading these blogs on the web.
Thank you for this clarification.
From what I've understand, you can easily use sockets like:
// main.js
this.sockets = {};
myOtherModule.init(sockets);
io.on('connection', function(socket)) {
sockets[socket.id] = socket;
socket.on('command', myOtherModule.onSocketCommand);
}
// myOtherModule.js
this.init = function(sockets) {
this.sockets = sockets;
}
this.onSocketCommand = function() {
this.sockets['other.socket.id'].emit('message');
}
You can always save the socket somewhere, no matter if it's within object or single variable. Then you can always use it to emit messages.

What is best way to use node.js and MSMQ?

I need create public queue with Microsoft Message Queuing(MSMQ) and send/receive messages from node.js server. What is best way to use node.js and MSMQ?
I'm interested in the "Fire-and-forget" model.
I too have the same use case. Whilst searching I stumbled across the node-msmq package on NPM/GitHub.
It is relatively new (May 2016) but I have had no issues with it to date. Simple API with a clear usage guide - worth a look.
Note: I'm not very sure this will be the answer but it helps
Try BusMQ is message bus and queueing system for node.js. Message queues are backed by Redis.
Code: https://github.com/capriza/node-busmq
var Bus = require('busmq');
var bus = Bus.create({redis: ['redis://127.0.0.1:6379']});
bus.on('online', function() {
var q = bus.queue('foo');
q.on('attached', function() {
console.log('attached to queue');
});
q.attach();
q.push({hello: 'world'});
q.push('my name if foo');
});
bus.connect();

Connecting to socket.io 1.x manually using websockets, capacity testing

I am working with a nodejs express server which uses socket.io to communicate an iOS client, and am having a little trouble trying to test how many clients can connect and exchange data at any one time.
My goal is to be able to run a script which connects to socket.io with thousands of different sessions, as well as send and receive data to understand our system's scale. Currently we are using a single dyno on Heroku but will likely be considering other options on AWS soon.
I have found code which should do what I am trying to do for earlier versions of socket.io, such as this, but have had issues since it seems v1.x has a very different handshake protocol. I tried out using the socket.io-client package, but trying to connect multiple times only simulates use of one session, I need to simulate many in independent users.
I have been picking apart the socket.io-client code, but have only gotten so far as creating a connection - I am stuck on the sending data part. If anyone has any knowledge or could point to some written resources on how data is sent between a client and a socket.io server, it would help me out a lot.
Here's what I have so far:
var needle = require('needle'),
WebSocket = require('ws'),
BASE_URL = 'url-to-socket-host:5002';
var connectionNo = 0;
needle.get('http://' + BASE_URL + '/socket.io/?EIO=3&transport=polling&t=1416506501335-0', function (err, resp) {
// parse the sid
var resp = JSON.parse(resp.body.toString().substring(5, resp.body.toString().length));
// use the sid to connect using websockets
var url = 'ws://' + BASE_URL + '/socket.io/?EIO=3&transport=websocket&sid=' + resp.sid;
console.log(connectionNo + ' with sid: ' + resp.sid);
var socket = new WebSocket(url, void(0), {
agent: false
});
socket.on('open', function () {
console.log('Websocket connected: ' + connectionNo);
// I don't understand how to send data to the server here,
// from looking at the source code it should use some kind
// of binary encoding, any ideas?
socket.on('message', function (msg) {
console.log(msg);
});
});
});
I will continue deconstructing the socket.io-client code but if anyone has any clues or recourses that may help, let me know. Thanks.
I ended up setting for using the socket.io-client npm package which has the ability to connect to a new session on every connection. I found an example benchmark in this issue.
There is not so much need for me to manually connect to socket.io using pure websockets and HTTP, but thanks to Yannik for pointing out the parser in use. The spec of the inner workings of v1.x can be found here.
Thanks!
The problem my reside in the fact that you are not using socket.io in your client code. You have imported ('ws') which is another module whose docs are here: https://www.npmjs.org/package/ws.
You probably want to ws.send('something');. When you receive a message in ws, it also comes with an object with a property indicating whether it is binary data or not. If it is, you will need to concatenate the chunks incrementally. There is a canonical way to do this which you can find via google. But it looks a little like this:
var message;
socketConnection.on('data', function(chunk){ message += chunk});

RabbitMQ and Sails.js

I'm having trouble using RabbitMQ with my Sails app. I'm unsure of where to place the subscriber code. What I'm trying to do is build a notifications system so that when an administrator approves a user's data request, the user's dashboard will pop a notification similar to how Facebook pops a notification. The problem is, putting the subscriber code in my dashboard controller's display route seems to never grab a published message.
Any advice would be greatly appreciated. Currently using rabbit.js package to connect to RabbitMQ.
To answer the original question, if one for some reason wanted to use Rabbit MQ instead of Sails' built-in resourceful pubsub, the best thing would be to use rabbit.js.
First, npm install rabbit.js.
Then, in your Sails project's config/sockets.js (borrowed liberally from the rabbit.js socket.io example):
var context = require('rabbit.js').createContext();
module.exports = {
onConnect: function(session, socket) {
var pub = context.socket('PUB');
var sub = context.socket('SUB');
socket.on('disconnect', function() {
pub.close();
sub.close();
});
// NB we have to adapt between the APIs
sub.setEncoding('utf8');
socket.on('message', function(msg) {
pub.write(msg, 'utf8');
});
sub.on('data', function(msg) {
socket.send(msg);
});
sub.connect('chat');
pub.connect('chat');
}
}
Here's an npm package that implements a RabbitMQ adapter for SailsJS.

Resources