Скрипт вывода статистики с криптокошельков

Материал из Linux Wiki
Перейти к навигацииПерейти к поиску

Используется jsonRPCClient.php отсюда

Полезная инфа, использованная для написания
getnetworkinfo:

version - идет в формате 6-7 чисел. Можно сделать обработку и делить точками (123456 => 0.12.34.56 или 1234567 => 1.23.45.67), но нова выбивается.
connections - альтернатива - вызвать getconnectioncount

-------------------------------

getblockchaininfo:

blocks - альтернатива - вызвать getblockcount
difficulty - альтернатива - вызвать getdifficulty
verificationprogress - домножить на 100 и округлить до 2-3 знака после запятой

-------------------------------

getmempoolinfo:

size - число транзакций
usage - байты. Делить на 1024/1024
usage/maxmempool - заполненность. Умножить на 100 и округлить до пары знаков.

-------------------------------

uptime - время работы кошелька (секунды)

-------------------------------

getmininginfo

тоже можно взять blocks и difficulty, как в getblockchaininfo, плюс есть число транз - pooledtx, есть скорость сети - networkhashps

-------------------------------

getnettotals:

totalbytesrecv - получено, байт
totalbytessent - отправлено, байт

-------------------------------

estimatesmartfee - комиссия. Аргумент - число блоков.

==============================================================
Особенности:
getmempoolinfo: Doge не отдает максимум (т.е., не можем знать процент) и usage, только bytes (бесполезно) NVC не отдает ничего.
uptime: не умеет никто, кроме btc
getmininginfo: difficulty на нове - массив для PoW и PoS. Скорость сети на нове зовется netmhashps вместо networkhashps.
estimatesmartfee: Doge и Нова не умеют. Для остальных - массив данных; забирать feerate
getblockchaininfo: все, кроме Новы. Нова не умеет ничего, кроме difficulty, но почему-то не отдает его через API.
getnetworkinfo: все, кроме новы. Нова не умеет метод.
<?php

// bitcoin api library
require_once 'jsonRPCClient.php';
date_default_timezone_set('Europe/Kiev');

$coindata = array();

// Coin names
$coindata['btc']  = array('name'=>'Bitcoin');
$coindata['ltc']  = array('name'=>'Litecoin');
$coindata['dash'] = array('name'=>'Dash');
$coindata['doge'] = array('name'=>'Dogecoin');
$coindata['zcash']  = array('name'=>'Zcash');
$coindata['nmc']  = array('name'=>'Namecoin');
$coindata['nvc']  = array('name'=>'Novacoin');

// RPC connection strings
$coindata['btc']['rpc']  = new jsonRPCClient('http://user:pass@127.0.0.1:8332/');
$coindata['ltc']['rpc']  = new jsonRPCClient('http://user:pass@127.0.0.1:9332/');
$coindata['dash']['rpc'] = new jsonRPCClient('http://user:pass@127.0.0.1:9998/');
$coindata['doge']['rpc'] = new jsonRPCClient('http://user:pass@127.0.0.1:22555/');
$coindata['zcash']['rpc']  = new jsonRPCClient('http://user:pass@127.0.0.1:8232/');
$coindata['nmc']['rpc']  = new jsonRPCClient('http://user:pass@127.0.0.1:8336/');
$coindata['nvc']['rpc']  = new jsonRPCClient('http://user:pass@127.0.0.1:8344/');
 
foreach ($coindata as $coin => $data){
// version info for all coins except  Nova
	try {
		$coindata[$coin]['getnetworkinfo'] = $data['rpc']->getnetworkinfo();
// version string transformations
		$coindata[$coin]['getnetworkinfo']['version'] = preg_replace('/\.00|^0+(?=[1-9])/', '', preg_replace('/\.0([1-9])/', '.\1', strrev(wordwrap(strrev(sprintf("%07d", $coindata[$coin]['getnetworkinfo']['version'])), 2, '.', true))));
	} catch (Exception $e) {
		$coindata[$coin]['getnetworkinfo'] = "";
		$coindata[$coin]['getnetworkinfo']['version'] = '<font color=red><b>OFFLINE</b></font>';
	}

// only for nova. all others have getnetworkinfo function with connections count in it. So, getconnectioncount() - universal way to get connections count
	try {$coindata[$coin]['connections'] = $data['rpc']->getconnectioncount();} catch (Exception $e) {$coindata[$coin]['connections'] = "n/a";}

// Mempool info: size (TXs count), usage and maximum size. No maximum and usage for Doge and no info at all for Nova
	try {
		$coindata[$coin]['mempool'] = $data['rpc']->getmempoolinfo();
		if (!isset($coindata[$coin]['mempool']['usage']))
			$coindata[$coin]['mempool']['usage']=NULL;
	} catch (Exception $e) {
		$coindata[$coin]['mempool']['size'] = 'n/a';
		$coindata[$coin]['mempool']['usage']=NULL;
	}

// only verificationprogress because of nvc
	try {
		$coindata[$coin]['blockchain'] = $data['rpc']->getblockchaininfo();
		$coindata[$coin]['blockchain']['verificationprogress']=round($coindata[$coin]['blockchain']['verificationprogress']*100, 3)." %";
	} catch (Exception $e) {
		$coindata[$coin]['blockchain']['verificationprogress'] = "n/a";
	}

// networkhashps (netmhashps for Nova), blocks, difficulty 
	try {$coindata[$coin]['mining'] = $data['rpc']->getmininginfo();} catch (Exception $e) {$coindata[$coin]['mining'] = "";}

// traffic - incoming/outgoing
	try {$coindata[$coin]['traf'] = $data['rpc']->getnettotals();} catch (Exception $e) {$coindata[$coin]['traf'] = "";}

// smart fee for 6 blocks. No info for Doge and Nova
	try {
		$coindata[$coin]['fee'] = $data['rpc']->estimatesmartfee(6);
		$coindata[$coin]['fee']['feerate'] = number_format($coindata[$coin]['fee']['feerate'], 8);
	} catch (Exception $e) {$coindata[$coin]['fee']['feerate'] = "n/a";}
}


// Novacoin >_<
try {
// Getting version info from getinfo for Nova
	$coindata['nvc']['getnetworkinfo']['version'] = $data['rpc']->getinfo();
// version info transformations
	$coindata['nvc']['getnetworkinfo']['version'] = preg_replace('/\-[a-zA-Z\-]+$|^[a-z\-]+(?=[0-9])/', '', $coindata['nvc']['getnetworkinfo']['version']['version']);

} catch (Exception $e) {$coindata[$coin]['getnetworkinfo']['version'] = "<font color=red><b>OFFLINE</b></font>";}

// netmhashps -> networkhashps for Nova
if (!empty($coindata['nvc']['mining']['netmhashps']))
	$coindata['nvc']['mining']['networkhashps'] = $coindata['nvc']['mining']['netmhashps']*1000000;

// Novacoin have 2 types of difficulty, so "difficulty" from getmininginfo is an array, not a value
if (!empty($coindata['nvc']['mining']['difficulty']))
	$coindata['nvc']['mining']['difficulty'] = "PoW: ".$coindata['nvc']['mining']['difficulty']['proof-of-work']." <br>PoS: ".$coindata['nvc']['mining']['difficulty']['proof-of-stake'];

// End of Novacoin

echo "
<html>
<head>
<meta http-equiv='refresh' content='600' charset='utf-8'>
<title>Cryptonode stats page. Last updated: ";

echo (strftime("%d/%m/%Y %H:%M:%S"));

echo "
</title>
</head>

<table>

<style type='text/css'>
   TABLE {
    width: 100%; /* Ширина таблицы */
    border-collapse: collapse; /* Убираем двойные линии между ячейками */
        font-size: 13px;
   }
   TD, TH {
    padding: 3px; /* Поля вокруг содержимого таблицы */
    border: 1px solid gray; /* Параметры рамки */
   }
   TH {
    background: #b0e0e6; /* Цвет фона */
   }
</style>

<tr align=center><td><b>Coin</b></td><td><b>Version</b></td><td><b>Blocks</b></td><td><b>Net Speed, Gh/s</b></td><td><b>Difficulty</b></td><td><b>Peers</b></td><td><b>Fee, Kb</b></td><td><b>Mem TXs</b></td><td><b>Mempool, KB</b></td><td><b>RX, MB</b></td><td><b>TX, MB</b></td><td><b>Synced</b></td></tr>
";

// table content is here
foreach ($coindata as $coin => $data){
	echo "<tr>
		<td>".$coindata[$coin]['name']."</td>
		<td align=center>".$coindata[$coin]['getnetworkinfo']['version']."</td>
		<td align=right>".$coindata[$coin]['mining']['blocks']."</td>
		<td align=right>".number_format($coindata[$coin]['mining']['networkhashps']/1000000000, 3, '.', ' ')."</td>
		<td align=right>".$coindata[$coin]['mining']['difficulty']."</td>
		<td align=center>".$coindata[$coin]['connections']."</td>
		<td align=center>".$coindata[$coin]['fee']['feerate']."</td>
		<td align=center>".$coindata[$coin]['mempool']['size']."</td>";
		if (isset($coindata[$coin]['mempool']['usage'])){
			echo "<td align=right>".round($coindata[$coin]['mempool']['usage']/1000, 2);
			if (isset($coindata[$coin]['mempool']['maxmempool'])){
				echo " (";
				echo number_format($coindata[$coin]['mempool']['usage']/$coindata[$coin]['mempool']['maxmempool']*100, 2);
				echo " %)";
			}
		}
			else
			echo "<td align=center>n/a";
		echo "</td>
		<td align=right>".round($coindata[$coin]['traf']['totalbytesrecv']/1000000, 2)."</td>
		<td align=right>".round($coindata[$coin]['traf']['totalbytessent']/1000000, 2)."</td>
		<td align=center>".$coindata[$coin]['blockchain']['verificationprogress']."</td>"
;
}
echo "</table>";

//echo "<pre>";
//	print_r($coindata);
//echo "</pre>";

?>