Skip to content

Instantly share code, notes, and snippets.

@rraallvv
Created June 28, 2020 22:31
Show Gist options
  • Save rraallvv/1966160dae2f2367c771ff1ffe236947 to your computer and use it in GitHub Desktop.
Save rraallvv/1966160dae2f2367c771ff1ffe236947 to your computer and use it in GitHub Desktop.
Nimiq Insight API
const START = Date.now();
const Nimiq = require('@nimiq/core');
require('dotenv').config();
const config = {
protocol: "dumb",
network: process.env.NETWORK || "main",
type: "nano"
};
const io = require("socket.io");
const server = io.listen(process.env.PORT);
// event fired every time a new client connects:
server.on("connection", (socket) => {
console.info(`Client connected [id=${socket.id}]`);
socket.on("disconnect", () => {
console.info(`Client gone [id=${socket.id}]`);
});
socket.on("subscribe", (data) => {
socket.join(data, () => {
console.info(`Subscribed ${data}`);
});
});
socket.on("unsubscribe", (data) => {
socket.leave(data, () => {
console.info(`Unsubscribed ${data}`);
});
});
});
/*
// sends test transactions
const dummy = {
txid: "...",
value: 123,
recipient: "NQ..."
};
setInterval(() => {
server.to('inv').emit('tx', dummy);
}, 5000);
*/
if (!Nimiq.GenesisConfig.CONFIGS[config.network]) {
console.error(`Invalid network name: ${config.network}`);
process.exit(1);
}
const TAG = 'Node';
const $ = {};
(async () => {
Nimiq.GenesisConfig.init(Nimiq.GenesisConfig.CONFIGS[config.network]);
let networkConfig = new Nimiq.DumbNetworkConfig();
$.consensus = await Nimiq.Consensus.nano(networkConfig);
$.blockchain = $.consensus.blockchain;
$.network = $.consensus.network;
Nimiq.Log.i(TAG, `Blockchain state: height=${$.blockchain.height}, headHash=${$.blockchain.headHash}`);
$.blockchain.on('head-changed', async (head) => {
if ($.consensus.established) {
const hash = await $.consensus.getHeadHash();
const block = await $.consensus.getBlock(hash, true);
const transactions = block.body.transactions;
for (const transaction of transactions) {
const address = transaction.recipient.toUserFriendlyAddress()
const data = {
txid: transaction.hash().toPlain(),
value: transaction.value,
recipient: address
};
server.to(address.replace(/ /g,'')).emit('tx', data);
console.log(`TX sent ${data.txid}`);
}
}
});
$.network.connect();
$.consensus.on('established', () => {
Nimiq.Log.i(TAG, `Blockchain ${config.type}-consensus established in ${(Date.now() - START) / 1000}s.`);
Nimiq.Log.i(TAG, `Current state: height=${$.blockchain.height}, totalWork=${$.blockchain.totalWork}, headHash=${$.blockchain.headHash}`);
});
})().catch(e => {
console.error(e);
process.exit(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment