Connecting A Bitcoin Personal Node Via Node.js

Follow

This tutorial shows a simple Node.js application that prints each new transaction as well as the total value of all the transactions outputs.

The following text assumes a basic working knowledge of Node.js and npm.

Install Node.js libraries

Install Node.js & NPM, downloads for your operating system can be found at https://nodejs.org/en/
Install the Node.js library 'bitcoind-zmq'. We will use this library to listen to the bitcoin events:

mkdir zmq-project && cd zmq-project
npm install bitcoind-zmq

The above command will initialize a Node.js project and create a package.json file with the dependency

Copy script

https://support.blockdaemon.com/hc/en-us/articles/360014669712-Your-Admin-DashboardCopy the following Node.js program into a file called index.js.

Update all “tcp://127.0.0.1” to your node's URL from the Connect page.
(Example: line 3, hashtx: 'tcp://127.0.0.1:28332, becomes hashtx: 'https://xxxxxxxx.bdnodes.net:28332, )

const BitcoindZmq = require('bitcoind-zmq')
const btcd = new BitcoindZmq({
hashtx: 'tcp://127.0.0.1:28332',
rawblock: 'tcp://127.0.0.1:28332',
hashblock: 'tcp://127.0.0.1:28333',
rawtx: 'tcp://127.0.0.1:28334'
})

btcd.connect()

btcd.on('hashblock', (hash) => {
console.log('got block hash:', hash) // hash <Buffer ... />
})

btcd.on('hashtx', (hash) => {
console.log('got tx hash:', hash) // hash <Buffer ... />
})

btcd.on('rawblock', (block) => {
console.log('got raw block:', block) // block <Buffer ... />
})

btcd.on('rawtx', (tx) => {
console.log('got raw tx:', tx) // tx <Buffer ... />
})

btcd.on('connect:*', (uri, type) => {
console.log(`socket ${type} connected to ${uri}`)
})

btcd.on('error:*', (err, type) => {
console.error(`${type} had error:`, err)
})

btcd.on('retry:*', (type, attempt) => {
console.log(`type: ${type}, retry attempt: ${attempt}`)
})

btcd.on('close:*', (err, type) => {
console.log(`close ${type}`, err || '')
})

Start the Node.js script, to connect and subscribe to Bitcoin ZMQ events

node index.js

Further Reading

"https://en.bitcoin.it/wiki/API_reference_(JSON-RPC)" Bitcoin RPC Protocol Documentation

"https://www.npmjs.com/package/bitcoind-zmq" bitcoind-zmq Documentation

0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.