ethstats-client/lib/node.js

367 lines
6.9 KiB
JavaScript
Raw Normal View History

2015-02-12 13:26:47 +01:00
var web3 = require('ethereum.js');
2015-02-17 02:07:40 +01:00
var _ = require('lodash');
2015-02-12 13:26:47 +01:00
var os = require('os');
2015-02-17 23:15:34 +01:00
var shelljs = require('shelljs');
2015-02-12 13:26:47 +01:00
2015-02-16 22:30:21 +01:00
var Primus = require('primus'),
Emitter = require('primus-emit'),
Socket;
Socket = Primus.createSocket({
transformer: 'websockets',
pathname: '/api',
plugin: {emitter: Emitter}
});
2015-02-17 23:15:34 +01:00
var INSTANCE_NAME,
ETH_VERSION;
if(process.env.NODE_ENV == 'production')
{
INSTANCE_NAME = shelljs.exec('ec2metadata --instance-id', {silent: true}).output;
ETH_VERSION = shelljs.exec('eth -V', {silent: true}).output;
}
2015-02-16 22:30:21 +01:00
var socket = new Socket(process.env.WS_SERVER || 'ws://localhost:3000');
2015-02-16 17:44:26 +01:00
2015-02-12 13:26:47 +01:00
var MAX_BLOCKS_HISTORY = 12,
LOWEST_TIMESTAMP = 0;
2015-02-12 22:59:01 +01:00
function Node()
2015-02-11 23:54:33 +01:00
{
2015-02-16 17:44:26 +01:00
var self = this;
2015-02-11 23:54:33 +01:00
this.info = {
2015-02-17 23:15:34 +01:00
name: INSTANCE_NAME || (process.env.EC2_INSTANCE_ID || os.hostname()),
node: ETH_VERSION || (process.env.ETH_VERSION || 'eth version 0.8.1'),
2015-02-12 13:26:47 +01:00
os: os.platform(),
os_v: os.release()
2015-02-11 23:54:33 +01:00
};
this.id = _.camelCase(this.info.name);
2015-02-17 02:07:40 +01:00
2015-02-12 14:38:09 +01:00
console.log(this.info);
2015-02-17 02:07:40 +01:00
2015-02-12 13:26:47 +01:00
this.stats = {
2015-02-11 23:54:33 +01:00
active: false,
2015-02-12 13:26:47 +01:00
listening: false,
2015-02-11 23:54:33 +01:00
mining: false,
2015-02-12 13:26:47 +01:00
peers: 0,
pending: 0,
gasPrice: 0,
block: {},
2015-02-17 02:07:40 +01:00
blocktimeAvg: 0,
2015-02-12 13:26:47 +01:00
difficulty: [],
2015-02-17 22:42:52 +01:00
txDensity: [],
uptime: 0,
2015-02-12 13:26:47 +01:00
errors: []
};
this._lastStats = JSON.stringify(this.stats);
this._tries = 0;
this._down = 0;
2015-02-11 23:54:33 +01:00
2015-02-17 02:07:40 +01:00
this.blocks = [];
2015-02-16 22:53:32 +01:00
this._socket = null;
2015-02-12 13:26:47 +01:00
this.pendingWatch = false;
this.chainWatch = false;
this.updateInterval = false;
2015-02-12 15:02:44 +01:00
web3.setProvider(new web3.providers.HttpSyncProvider('http://' + (process.env.RPC_HOST || 'localhost') + ':' + (process.env.RPC_PORT || '8080')));
2015-02-11 23:54:33 +01:00
2015-02-16 22:30:21 +01:00
socket.on('open', function open() {
socket.emit('hello', { id: self.id, info: self.info});
2015-02-16 22:30:21 +01:00
console.log('The connection has been opened.');
}).on('end', function end() {
2015-02-16 22:53:32 +01:00
self._socket = false;
2015-02-16 22:30:21 +01:00
}).on('error', function error(err) {
console.log(err);
}).on('reconnecting', function reconnecting(opts) {
console.log('We are scheduling a reconnect operation', opts);
}).on('data', function incoming(data) {
console.log('Received some data', data);
2015-02-16 17:44:26 +01:00
});
2015-02-11 23:54:33 +01:00
socket.on('ready', function()
{
if(self.changed())
{
self._socket = true;
self.sendUpdate(true);
}
console.log('The connection has been established.');
})
2015-02-17 02:07:40 +01:00
this.init();
2015-02-11 23:54:33 +01:00
2015-02-17 02:07:40 +01:00
return this;
2015-02-12 14:38:09 +01:00
}
2015-02-12 13:26:47 +01:00
Node.prototype.isActive = function()
2015-02-11 23:54:33 +01:00
{
this._tries++;
2015-02-12 13:26:47 +01:00
this.stats.errors = [];
2015-02-11 23:54:33 +01:00
try {
2015-02-12 13:26:47 +01:00
this.stats.peers = web3.eth.peerCount;
this.stats.active = true;
return true;
2015-02-11 23:54:33 +01:00
}
catch (err) {
2015-02-12 13:26:47 +01:00
this.stats.active = false;
this.stats.listening = false;
this.stats.mining = false;
this.stats.peers = 0;
this._down++;
2015-02-12 13:26:47 +01:00
this.stats.errors.push({
code: '1',
msg: err
});
return false;
2015-02-11 23:54:33 +01:00
}
2015-02-12 13:26:47 +01:00
}
Node.prototype.getBlock = function(number)
{
var block = {
number: 0,
hash: '?',
difficulty: 0,
timestamp: 0
};
2015-02-11 23:54:33 +01:00
2015-02-12 13:26:47 +01:00
if(typeof number === 'undefined'){
try {
number = parseInt(web3.eth.number);
if(number === this.stats.block.number + 1)
return this.stats.block;
}
catch (err) {
this.stats.errors.push({
code: '3',
msg: err
});
2015-02-11 23:54:33 +01:00
}
}
2015-02-12 13:26:47 +01:00
try {
block = web3.eth.block(number);
if(block.hash != '?' && typeof block.difficulty !== 'undefined')
{
block.difficulty = web3.toDecimal(block.difficulty);
2015-02-17 22:42:52 +01:00
try {
block.txCount = web3.eth.transactionCount(block.hash);
}
catch (err) {
console.log(err);
}
2015-02-12 13:26:47 +01:00
}
}
catch (err) {
this.stats.errors.push({
code: '2',
msg: err
});
}
return block;
}
Node.prototype.getLatestBlocks = function()
{
var bestBlock = this.stats.block.number;
var maxIterations = MAX_BLOCKS_HISTORY;
var minBlock = 0;
2015-02-17 02:07:40 +01:00
if(this.blocks.length > 0)
2015-02-12 13:26:47 +01:00
{
2015-02-17 02:07:40 +01:00
maxIterations = Math.min(bestBlock - this.blocks[0].number, MAX_BLOCKS_HISTORY);
2015-02-12 13:26:47 +01:00
}
minBlock = Math.max(0, parseInt(bestBlock) - maxIterations);
for (var i = minBlock; i < bestBlock; i++)
{
this.addBlockHistory(this.getBlock(i));
};
this.addBlockHistory(this.stats.block);
this.calculateBlockTimes();
this.stats.blocktimeAvg = this.blockTimesAvg();
this.stats.difficulty = this.difficultyChart();
2015-02-17 22:42:52 +01:00
this.stats.txDensity = this.txDensityChart();
2015-02-12 13:26:47 +01:00
}
Node.prototype.addBlockHistory = function(block)
{
2015-02-17 02:07:40 +01:00
if(this.blocks.length === 0 || block.number != this.blocks[0].number)
2015-02-12 13:26:47 +01:00
{
2015-02-17 02:07:40 +01:00
if(this.blocks.length === MAX_BLOCKS_HISTORY)
{
LOWEST_TIMESTAMP = this.blocks[MAX_BLOCKS_HISTORY - 1].timestamp;
this.blocks.pop();
}
2015-02-12 13:26:47 +01:00
2015-02-17 02:07:40 +01:00
this.blocks.unshift(block);
}
2015-02-12 13:26:47 +01:00
}
2015-02-11 23:54:33 +01:00
2015-02-12 13:26:47 +01:00
Node.prototype.calculateBlockTimes = function()
{
var self = this;
2015-02-17 02:07:40 +01:00
var blockTimes = _.map(this.blocks, function(block, key, list)
2015-02-12 13:26:47 +01:00
{
var diff = block.timestamp - (key < list.length - 1 ? list[key + 1].timestamp : LOWEST_TIMESTAMP);
2015-02-17 02:07:40 +01:00
self.blocks[key].blocktime = diff;
2015-02-12 13:26:47 +01:00
return diff;
});
return blockTimes;
}
Node.prototype.blockTimesAvg = function()
{
2015-02-17 02:07:40 +01:00
var sum = _.reduce(this.blocks, function(memo, block) { return memo + block.blocktime;}, 0);
2015-02-12 13:26:47 +01:00
2015-02-17 02:07:40 +01:00
return sum/this.blocks.length;
2015-02-12 13:26:47 +01:00
}
Node.prototype.difficultyChart = function()
{
2015-02-17 02:07:40 +01:00
return difficulty = _.map(this.blocks, function(block)
2015-02-12 13:26:47 +01:00
{
return block.difficulty;
});
}
2015-02-17 22:42:52 +01:00
Node.prototype.txDensityChart = function()
{
return txDensity = _.map(this.blocks, function(block)
{
return block.txCount;
});
}
2015-02-12 13:26:47 +01:00
Node.prototype.uptime = function()
{
this.stats.uptime = ((this._tries - this._down) / this._tries) * 100;
2015-02-12 13:26:47 +01:00
}
Node.prototype.getStats = function()
{
if(this._socket)
this._lastStats = JSON.stringify(this.stats);
2015-02-12 13:26:47 +01:00
if(this.isActive())
{
this.stats.block = this.getBlock();
// Get last MAX_BLOCKS_HISTORY blocks for calculations
if(this.stats.block.number > 0)
this.getLatestBlocks();
this.stats.mining = web3.eth.mining;
this.stats.gasPrice = web3.toDecimal(web3.eth.gasPrice);
this.stats.listening = web3.eth.listening;
}
this.uptime();
}
Node.prototype.changed = function()
{
var changed = ! _.isEqual(this._lastStats, JSON.stringify(this.stats));
console.log(changed);
return changed;
}
2015-02-12 15:02:44 +01:00
Node.prototype.prepareStats = function()
{
return {
id: this.id,
2015-02-12 15:02:44 +01:00
stats: this.stats
};
}
Node.prototype.sendUpdate = function(force)
{
if(this.changed() || force)
this.emit('update', this.prepareStats());
}
2015-02-12 13:26:47 +01:00
Node.prototype.update = function()
{
this.getStats();
this.sendUpdate();
2015-02-12 15:02:44 +01:00
2015-02-12 13:26:47 +01:00
return this.stats;
2015-02-11 23:54:33 +01:00
};
2015-02-12 13:26:47 +01:00
Node.prototype.setWatches = function()
{
var self = this;
2015-02-17 02:07:40 +01:00
2015-02-12 13:26:47 +01:00
this.pendingWatch = web3.eth.watch('pending');
this.pendingWatch.changed(function(log) {
console.log('pending changed');
2015-02-17 02:07:40 +01:00
self.stats.pending = parseInt(log.number);
2015-02-12 13:26:47 +01:00
});
this.chainWatch = web3.eth.watch('chain');
this.chainWatch.messages(function(log) {
console.log('block changed');
self.update();
});
this.updateInterval = setInterval(function(){
self.update();
}, 1000);
}
2015-02-16 17:44:26 +01:00
Node.prototype.emit = function(message, payload)
2015-02-12 13:26:47 +01:00
{
2015-02-16 22:53:32 +01:00
if(this._socket){
2015-02-16 17:44:26 +01:00
try {
socket.emit(message, payload);
}
catch (err) {
console.log(err);
}
}
}
2015-02-12 15:02:44 +01:00
2015-02-16 17:44:26 +01:00
Node.prototype.init = function()
{
2015-02-12 13:26:47 +01:00
this.update();
this.setWatches();
}
Node.prototype.stop = function()
{
2015-02-16 22:53:32 +01:00
if(this._socket)
2015-02-16 22:30:21 +01:00
socket.end(socket.id);
2015-02-12 15:02:44 +01:00
2015-02-12 13:26:47 +01:00
if(this.updateInterval)
clearInterval(this.updateInterval);
if(this.pendingWatch)
this.pendingWatch.uninstall();
if(this.chainWatch)
this.chainWatch.uninstall();
}
2015-02-11 23:54:33 +01:00
module.exports = Node;