wallet/getnodeinfo
Real-Time Node Monitoring
Dwellir's TRON infrastructure provides instant node status with version info, sync state, and network connectivity. Monitor node health and configuration for optimal integration.
Retrieve detailed information about the connected TRON node including software version, network configuration, current block height, and peer connections.
Use Cases
wallet/getnodeinfo
is crucial for:
- Health Monitoring - Check node status and sync state
- Version Tracking - Verify node software version
- Network Analysis - Monitor peer connections
- Configuration Audit - Review node settings
- Debugging - Troubleshoot connection issues
Parameters
This method requires no parameters.
Request Example
{}
Response Fields
Field | Type | Description |
---|---|---|
beginSyncNum | number | Block number when sync started |
block | string | Current block hash and height |
solidityBlock | string | Latest solidified block |
currentConnectCount | number | Current peer connections |
activeConnectCount | number | Active peer connections |
passiveConnectCount | number | Passive peer connections |
totalFlow | number | Total network traffic |
peerList | array | Connected peer information |
configNodeInfo | object | Node configuration details |
machineInfo | object | Hardware and OS information |
cheatWitnessInfoMap | object | Witness validation info |
Implementation Examples
- JavaScript
- Python
- cURL
const TRON_API = 'https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY';
// Get basic node information
async function getNodeInfo() {
const response = await fetch(`${TRON_API}/wallet/getnodeinfo`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
}
// Comprehensive node monitor
class TronNodeMonitor {
constructor(apiKey) {
this.apiUrl = `https://api-tron-mainnet.n.dwellir.com/${apiKey}`;
this.lastInfo = null;
this.alerts = [];
}
async fetchNodeInfo() {
const response = await fetch(`${this.apiUrl}/wallet/getnodeinfo`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({})
});
if (!response.ok) {
throw new Error(`Node info request failed: ${response.statusText}`);
}
return await response.json();
}
async getStatus() {
try {
const info = await this.fetchNodeInfo();
// Parse block information
const blockInfo = this.parseBlockInfo(info.block);
const solidityBlockInfo = this.parseBlockInfo(info.solidityBlock);
// Calculate sync status
const syncLag = blockInfo.number - solidityBlockInfo.number;
const isSynced = syncLag < 100; // Consider synced if less than 100 blocks behind
return {
online: true,
version: info.configNodeInfo?.codeVersion || 'Unknown',
network: info.configNodeInfo?.network || 'mainnet',
currentBlock: blockInfo.number,
solidityBlock: solidityBlockInfo.number,
syncLag: syncLag,
isSynced: isSynced,
peers: {
total: info.currentConnectCount || 0,
active: info.activeConnectCount || 0,
passive: info.passiveConnectCount || 0
},
traffic: this.formatBytes(info.totalFlow || 0),
timestamp: new Date().toISOString()
};
} catch (error) {
return {
online: false,
error: error.message,
timestamp: new Date().toISOString()
};
}
}
parseBlockInfo(blockString) {
if (!blockString) return { hash: null, number: 0 };
// Format: "Num:12345,ID:hash"
const parts = blockString.split(',');
const num = parts[0]?.split(':')[1] || '0';
const id = parts[1]?.split(':')[1] || '';
return {
number: parseInt(num, 10),
hash: id
};
}
async getDetailedInfo() {
const info = await this.fetchNodeInfo();
return {
basic: {
version: info.configNodeInfo?.codeVersion,
network: info.configNodeInfo?.network,
dbVersion: info.configNodeInfo?.dbVersion,
p2pVersion: info.configNodeInfo?.p2pVersion
},
sync: {
beginBlock: info.beginSyncNum,
currentBlock: this.parseBlockInfo(info.block).number,
solidityBlock: this.parseBlockInfo(info.solidityBlock).number,
needSync: info.needSync
},
network: {
listenPort: info.configNodeInfo?.listenPort,
discoveryEnabled: info.configNodeInfo?.discoverEnabled,
activeNodes: info.configNodeInfo?.activeNodeSize,
passiveNodes: info.configNodeInfo?.passiveNodeSize,
maxConnections: info.configNodeInfo?.maxConnectCount
},
peers: this.analyzePeers(info.peerList || []),
machine: {
cpuCount: info.machineInfo?.cpuCount,
cpuRate: info.machineInfo?.cpuRate,
memoryUsage: info.machineInfo?.memoryDescInfo,
javaVersion: info.machineInfo?.javaVersion,
osName: info.machineInfo?.osName,
totalMemory: info.machineInfo?.totalMemory,
freeMemory: info.machineInfo?.freeMemory
}
};
}
analyzePeers(peerList) {
const analysis = {
total: peerList.length,
byVersion: {},
byCountry: {},
avgLatency: 0,
topPeers: []
};
let totalLatency = 0;
peerList.forEach(peer => {
// Count by version
const version = peer.nodeInfo?.codeVersion || 'Unknown';
analysis.byVersion[version] = (analysis.byVersion[version] || 0) + 1;
// Track latency
if (peer.avgLatency) {
totalLatency += peer.avgLatency;
}
// Add to top peers
analysis.topPeers.push({
address: peer.host,
port: peer.port,
latency: peer.avgLatency,
version: version,
blockHeight: peer.blockInNum,
connected: peer.connectTime
});
});
// Calculate average latency
if (peerList.length > 0) {
analysis.avgLatency = Math.round(totalLatency / peerList.length);
}
// Sort top peers by block height
analysis.topPeers.sort((a, b) => b.blockHeight - a.blockHeight);
analysis.topPeers = analysis.topPeers.slice(0, 10);
return analysis;
}
async monitorHealth(intervalMs = 60000) {
const checkHealth = async () => {
const status = await this.getStatus();
// Check for issues
if (!status.online) {
this.addAlert('error', 'Node is offline', status);
} else if (!status.isSynced) {
this.addAlert('warning', `Node is ${status.syncLag} blocks behind`, status);
} else if (status.peers.total < 5) {
this.addAlert('warning', `Low peer count: ${status.peers.total}`, status);
}
this.lastInfo = status;
return status;
};
// Initial check
await checkHealth();
// Set up monitoring interval
return setInterval(checkHealth, intervalMs);
}
addAlert(level, message, data) {
const alert = {
level,
message,
data,
timestamp: new Date().toISOString()
};
this.alerts.push(alert);
// Keep only last 100 alerts
if (this.alerts.length > 100) {
this.alerts = this.alerts.slice(-100);
}
// Trigger alert handler if configured
this.onAlert?.(alert);
}
getAlerts(level = null) {
if (level) {
return this.alerts.filter(a => a.level === level);
}
return this.alerts;
}
formatBytes(bytes) {
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 B';
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
}
}
// Dashboard component
class NodeDashboard {
constructor(apiKey) {
this.monitor = new TronNodeMonitor(apiKey);
this.updateInterval = null;
}
async start(elementId, refreshInterval = 30000) {
const container = document.getElementById(elementId);
if (!container) return;
const update = async () => {
const status = await this.monitor.getStatus();
container.innerHTML = this.renderDashboard(status);
};
// Initial render
await update();
// Set up auto-refresh
this.updateInterval = setInterval(update, refreshInterval);
}
renderDashboard(status) {
if (!status.online) {
return `
<div class="node-dashboard error">
<h3>⚠️ Node Offline</h3>
<p>Error: ${status.error}</p>
<p>Last check: ${status.timestamp}</p>
</div>
`;
}
const syncStatus = status.isSynced ?
'<span class="badge success">Synced</span>' :
`<span class="badge warning">Syncing (${status.syncLag} blocks behind)</span>`;
return `
<div class="node-dashboard">
<h3>TRON Node Status</h3>
<div class="status-grid">
<div class="status-item">
<label>Version:</label>
<span>${status.version}</span>
</div>
<div class="status-item">
<label>Network:</label>
<span>${status.network}</span>
</div>
<div class="status-item">
<label>Current Block:</label>
<span>${status.currentBlock.toLocaleString()}</span>
</div>
<div class="status-item">
<label>Sync Status:</label>
${syncStatus}
</div>
<div class="status-item">
<label>Peers:</label>
<span>${status.peers.total} (${status.peers.active} active)</span>
</div>
<div class="status-item">
<label>Traffic:</label>
<span>${status.traffic}</span>
</div>
</div>
<p class="updated">Updated: ${new Date(status.timestamp).toLocaleTimeString()}</p>
</div>
`;
}
stop() {
if (this.updateInterval) {
clearInterval(this.updateInterval);
this.updateInterval = null;
}
}
}
// Usage examples
(async () => {
const monitor = new TronNodeMonitor('YOUR_API_KEY');
try {
// Get basic status
const status = await monitor.getStatus();
console.log('Node Status:', status);
// Get detailed information
const detailed = await monitor.getDetailedInfo();
console.log('Detailed Info:', detailed);
// Set up health monitoring
monitor.onAlert = (alert) => {
console.log(`[${alert.level.toUpperCase()}] ${alert.message}`);
};
const monitorHandle = await monitor.monitorHealth(60000);
// Start dashboard (if in browser)
if (typeof document !== 'undefined') {
const dashboard = new NodeDashboard('YOUR_API_KEY');
await dashboard.start('node-status', 30000);
}
// Stop monitoring after 5 minutes
setTimeout(() => {
clearInterval(monitorHandle);
console.log('Monitoring stopped');
}, 5 * 60 * 1000);
} catch (error) {
console.error('Error:', error);
}
})();
import requests
import json
from typing import Dict, List, Optional
from datetime import datetime
import time
from threading import Thread, Event
class TronNodeMonitor:
def __init__(self, api_key: str):
self.base_url = f"https://api-tron-mainnet.n.dwellir.com/{api_key}"
self.headers = {'Content-Type': 'application/json'}
self.last_info = None
self.alerts = []
def get_node_info(self) -> Dict:
"""
Fetch raw node information
"""
url = f"{self.base_url}/wallet/getnodeinfo"
try:
response = requests.post(url, headers=self.headers, json={})
response.raise_for_status()
return response.json()
except requests.RequestException as e:
raise Exception(f"Failed to get node info: {str(e)}")
def get_status(self) -> Dict:
"""
Get formatted node status
"""
try:
info = self.get_node_info()
# Parse block information
block_info = self._parse_block_info(info.get('block', ''))
solidity_block_info = self._parse_block_info(info.get('solidityBlock', ''))
# Calculate sync status
sync_lag = block_info['number'] - solidity_block_info['number']
is_synced = sync_lag < 100
return {
'online': True,
'version': info.get('configNodeInfo', {}).get('codeVersion', 'Unknown'),
'network': info.get('configNodeInfo', {}).get('network', 'mainnet'),
'current_block': block_info['number'],
'solidity_block': solidity_block_info['number'],
'sync_lag': sync_lag,
'is_synced': is_synced,
'peers': {
'total': info.get('currentConnectCount', 0),
'active': info.get('activeConnectCount', 0),
'passive': info.get('passiveConnectCount', 0)
},
'traffic': self._format_bytes(info.get('totalFlow', 0)),
'timestamp': datetime.now().isoformat()
}
except Exception as e:
return {
'online': False,
'error': str(e),
'timestamp': datetime.now().isoformat()
}
def _parse_block_info(self, block_string: str) -> Dict:
"""
Parse block string format: 'Num:12345,ID:hash'
"""
if not block_string:
return {'hash': None, 'number': 0}
parts = block_string.split(',')
num = 0
hash_id = ''
for part in parts:
if 'Num:' in part:
num = int(part.split(':')[1])
elif 'ID:' in part:
hash_id = part.split(':')[1]
return {'number': num, 'hash': hash_id}
def get_detailed_info(self) -> Dict:
"""
Get comprehensive node information
"""
info = self.get_node_info()
config = info.get('configNodeInfo', {})
machine = info.get('machineInfo', {})
return {
'basic': {
'version': config.get('codeVersion'),
'network': config.get('network'),
'db_version': config.get('dbVersion'),
'p2p_version': config.get('p2pVersion'),
'min_participation_rate': config.get('minParticipationRate'),
'support_constant': config.get('supportConstant')
},
'sync': {
'begin_block': info.get('beginSyncNum'),
'current_block': self._parse_block_info(info.get('block', ''))['number'],
'solidity_block': self._parse_block_info(info.get('solidityBlock', ''))['number'],
'need_sync': info.get('needSync', False)
},
'network': {
'listen_port': config.get('listenPort'),
'discovery_enabled': config.get('discoverEnabled'),
'active_nodes': config.get('activeNodeSize'),
'passive_nodes': config.get('passiveNodeSize'),
'max_connections': config.get('maxConnectCount'),
'same_ip_max_count': config.get('sameIpMaxConnectCount'),
'backup_priority': config.get('backupPriority')
},
'peers': self._analyze_peers(info.get('peerList', [])),
'machine': {
'cpu_count': machine.get('cpuCount'),
'cpu_rate': machine.get('cpuRate'),
'memory': machine.get('memoryDescInfo'),
'java_version': machine.get('javaVersion'),
'os_name': machine.get('osName'),
'total_memory': machine.get('totalMemory'),
'free_memory': machine.get('freeMemory'),
'dead_lock_thread_count': machine.get('deadLockThreadCount')
},
'witnesses': self._analyze_witnesses(info.get('cheatWitnessInfoMap', {}))
}
def _analyze_peers(self, peer_list: List[Dict]) -> Dict:
"""
Analyze peer connections
"""
analysis = {
'total': len(peer_list),
'by_version': {},
'avg_latency': 0,
'top_peers': []
}
if not peer_list:
return analysis
total_latency = 0
for peer in peer_list:
# Count by version
version = peer.get('nodeInfo', {}).get('codeVersion', 'Unknown')
analysis['by_version'][version] = analysis['by_version'].get(version, 0) + 1
# Track latency
latency = peer.get('avgLatency', 0)
total_latency += latency
# Add to top peers
analysis['top_peers'].append({
'address': peer.get('host'),
'port': peer.get('port'),
'latency': latency,
'version': version,
'block_height': peer.get('blockInNum', 0),
'connected_time': peer.get('connectTime')
})
# Calculate average latency
analysis['avg_latency'] = round(total_latency / len(peer_list))
# Sort and limit top peers
analysis['top_peers'].sort(key=lambda x: x['block_height'], reverse=True)
analysis['top_peers'] = analysis['top_peers'][:10]
return analysis
def _analyze_witnesses(self, witness_map: Dict) -> Dict:
"""
Analyze witness information
"""
if not witness_map:
return {'total': 0, 'witnesses': []}
witnesses = []
for address, info in witness_map.items():
witnesses.append({
'address': address,
'vote_count': info.get('voteCount', 0),
'latest_block': info.get('latestBlockNum', 0)
})
witnesses.sort(key=lambda x: x['vote_count'], reverse=True)
return {
'total': len(witnesses),
'witnesses': witnesses[:20] # Top 20 witnesses
}
def monitor_health(self, check_interval: int = 60) -> Thread:
"""
Start health monitoring in background thread
"""
stop_event = Event()
def monitor_loop():
while not stop_event.is_set():
status = self.get_status()
# Check for issues
if not status['online']:
self._add_alert('error', 'Node is offline', status)
elif not status['is_synced']:
self._add_alert('warning', f"Node is {status['sync_lag']} blocks behind", status)
elif status['peers']['total'] < 5:
self._add_alert('warning', f"Low peer count: {status['peers']['total']}", status)
self.last_info = status
stop_event.wait(check_interval)
thread = Thread(target=monitor_loop, daemon=True)
thread.stop_event = stop_event
thread.start()
return thread
def _add_alert(self, level: str, message: str, data: Dict):
"""
Add alert to list
"""
alert = {
'level': level,
'message': message,
'data': data,
'timestamp': datetime.now().isoformat()
}
self.alerts.append(alert)
# Keep only last 100 alerts
if len(self.alerts) > 100:
self.alerts = self.alerts[-100:]
def get_alerts(self, level: Optional[str] = None) -> List[Dict]:
"""
Get alerts, optionally filtered by level
"""
if level:
return [a for a in self.alerts if a['level'] == level]
return self.alerts
def _format_bytes(self, bytes_value: int) -> str:
"""
Format bytes to human-readable string
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if bytes_value < 1024.0:
return f"{bytes_value:.2f} {unit}"
bytes_value /= 1024.0
return f"{bytes_value:.2f} PB"
class NodeStatusReporter:
"""
Generate node status reports
"""
def __init__(self, monitor: TronNodeMonitor):
self.monitor = monitor
def generate_report(self) -> str:
"""
Generate comprehensive status report
"""
status = self.monitor.get_status()
detailed = self.monitor.get_detailed_info()
report = []
report.append("=" * 50)
report.append("TRON Node Status Report")
report.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
report.append("=" * 50)
# Basic status
report.append("\n[STATUS]")
report.append(f"Online: {'✓' if status['online'] else '✗'}")
if status['online']:
report.append(f"Version: {status['version']}")
report.append(f"Network: {status['network']}")
report.append(f"Synced: {'✓' if status['is_synced'] else '✗'}")
report.append(f"Current Block: {status['current_block']:,}")
report.append(f"Solidity Block: {status['solidity_block']:,}")
report.append(f"Sync Lag: {status['sync_lag']} blocks")
else:
report.append(f"Error: {status.get('error')}")
# Network info
report.append("\n[NETWORK]")
report.append(f"Total Peers: {status['peers']['total']}")
report.append(f"Active Peers: {status['peers']['active']}")
report.append(f"Passive Peers: {status['peers']['passive']}")
report.append(f"Network Traffic: {status['traffic']}")
# Machine info
if detailed['machine']['cpu_count']:
report.append("\n[MACHINE]")
report.append(f"CPU Count: {detailed['machine']['cpu_count']}")
report.append(f"CPU Usage: {detailed['machine']['cpu_rate']}%")
report.append(f"Memory: {detailed['machine']['memory']}")
report.append(f"OS: {detailed['machine']['os_name']}")
# Top peers
if detailed['peers']['top_peers']:
report.append("\n[TOP PEERS]")
for peer in detailed['peers']['top_peers'][:5]:
report.append(f" - {peer['address']}:{peer['port']} "
f"(Block: {peer['block_height']:,}, "
f"Latency: {peer['latency']}ms)")
# Recent alerts
recent_alerts = self.monitor.get_alerts()[-5:]
if recent_alerts:
report.append("\n[RECENT ALERTS]")
for alert in recent_alerts:
report.append(f" [{alert['level'].upper()}] {alert['message']}")
report.append("\n" + "=" * 50)
return "\n".join(report)
# Usage examples
if __name__ == "__main__":
monitor = TronNodeMonitor('YOUR_API_KEY')
reporter = NodeStatusReporter(monitor)
try:
# Get basic status
print("Fetching node status...")
status = monitor.get_status()
if status['online']:
print(f"✓ Node Online - Version {status['version']}")
print(f" Current Block: {status['current_block']:,}")
print(f" Sync Status: {'Synced' if status['is_synced'] else f'{status['sync_lag']} blocks behind'}")
print(f" Peers: {status['peers']['total']}")
else:
print(f"✗ Node Offline - {status['error']}")
# Get detailed information
print("\nFetching detailed information...")
detailed = monitor.get_detailed_info()
print(f"\nNetwork Configuration:")
print(f" Listen Port: {detailed['network']['listen_port']}")
print(f" Max Connections: {detailed['network']['max_connections']}")
print(f" Discovery Enabled: {detailed['network']['discovery_enabled']}")
print(f"\nPeer Analysis:")
print(f" Total Peers: {detailed['peers']['total']}")
print(f" Average Latency: {detailed['peers']['avg_latency']}ms")
print(f" Version Distribution:")
for version, count in detailed['peers']['by_version'].items():
print(f" {version}: {count} peers")
# Generate full report
print("\n" + reporter.generate_report())
# Start monitoring (optional)
print("\nStarting health monitoring (press Ctrl+C to stop)...")
monitor_thread = monitor.monitor_health(30)
try:
while True:
time.sleep(60)
# Print any new alerts
new_alerts = monitor.get_alerts()[-1:]
for alert in new_alerts:
print(f"[{datetime.now().strftime('%H:%M:%S')}] "
f"[{alert['level'].upper()}] {alert['message']}")
except KeyboardInterrupt:
print("\nStopping monitor...")
monitor_thread.stop_event.set()
monitor_thread.join()
except Exception as e:
print(f"Error: {e}")
# Get node information
curl -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnodeinfo" \
-H "Content-Type: application/json" \
-d '{}'
# Parse basic info with jq
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnodeinfo" \
-H "Content-Type: application/json" \
-d '{}' | jq '{
version: .configNodeInfo.codeVersion,
network: .configNodeInfo.network,
current_block: .block,
solidity_block: .solidityBlock,
peers: .currentConnectCount,
active_peers: .activeConnectCount
}'
# Get sync status
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnodeinfo" \
-H "Content-Type: application/json" \
-d '{}' | jq '{
current: (.block | split(",")[0] | split(":")[1] | tonumber),
solidity: (.solidityBlock | split(",")[0] | split(":")[1] | tonumber),
lag: ((.block | split(",")[0] | split(":")[1] | tonumber) -
(.solidityBlock | split(",")[0] | split(":")[1] | tonumber))
}'
# Monitor node status script
#!/bin/bash
API_KEY="YOUR_API_KEY"
while true; do
echo "=== TRON Node Status - $(date) ==="
response=$(curl -s -X POST \
"https://api-tron-mainnet.n.dwellir.com/$API_KEY/wallet/getnodeinfo" \
-H "Content-Type: application/json" \
-d '{}')
if [ $? -eq 0 ]; then
echo "✓ Node Online"
echo "$response" | jq -r '
"Version: " + .configNodeInfo.codeVersion,
"Network: " + .configNodeInfo.network,
"Peers: " + (.currentConnectCount | tostring),
"Block: " + .block
'
else
echo "✗ Node Offline"
fi
echo ""
sleep 30
done
# Extract peer information
curl -s -X POST "https://api-tron-mainnet.n.dwellir.com/YOUR_API_KEY/wallet/getnodeinfo" \
-H "Content-Type: application/json" \
-d '{}' | jq '
{
peer_count: .peerList | length,
top_peers: [.peerList[] | {
host: .host,
port: .port,
version: .nodeInfo.codeVersion,
latency: .avgLatency
}] | sort_by(.latency) | .[0:5]
}'
Response Example
{
"beginSyncNum": 58000000,
"block": "Num:58234567,ID:0000000003787ac74d9bb8f8c9c59ac3f3e3b9b8c9e3e8f9",
"solidityBlock": "Num:58234547,ID:0000000003787ab34d9bb8f8c9c59ac3f3e3b9b8c9e3e8f8",
"currentConnectCount": 30,
"activeConnectCount": 18,
"passiveConnectCount": 12,
"totalFlow": 1234567890,
"peerList": [
{
"host": "192.168.1.100",
"port": 18888,
"avgLatency": 45,
"blockInNum": 58234567,
"connectTime": 1702456789000,
"nodeInfo": {
"codeVersion": "4.7.2",
"p2pVersion": "1.0.0"
}
}
],
"configNodeInfo": {
"codeVersion": "4.7.2",
"versionName": "GreatVoyage-v4.7.2",
"versionNum": "17766",
"p2pVersion": "11111",
"listenPort": 18888,
"discoverEnable": true,
"activeNodeSize": 18,
"passiveNodeSize": 12,
"sendNodeSize": 30,
"maxConnectCount": 50,
"sameIpMaxConnectCount": 2,
"backupListenPort": 10001,
"backupMemberSize": 0,
"backupPriority": 8,
"dbVersion": 2,
"minParticipationRate": 15,
"supportConstant": true,
"minTimeRatio": 0.6,
"maxTimeRatio": 5.0,
"allowCreationOfContracts": 0,
"allowAdaptiveEnergy": 0
},
"machineInfo": {
"threadCount": 150,
"deadLockThreadCount": 0,
"cpuCount": 16,
"totalMemory": 34359738368,
"freeMemory": 12884901888,
"cpuRate": 0.35,
"javaVersion": "1.8.0_292",
"osName": "Linux",
"jvmTotalMemory": 8589934592,
"jvmFreeMemory": 4294967296,
"processCpuRate": 0.25,
"memoryDescInfo": "Total: 32GB, Free: 12GB, Usage: 62.5%",
"deadLockThreadInfoList": []
},
"cheatWitnessInfoMap": {}
}
Common Use Cases
1. Health Check Endpoint
async function healthCheck() {
try {
const info = await getNodeInfo();
const blockInfo = parseBlockString(info.block);
const solidityInfo = parseBlockString(info.solidityBlock);
const healthy =
info.currentConnectCount > 5 &&
(blockInfo.number - solidityInfo.number) < 100;
return {
status: healthy ? 'healthy' : 'degraded',
details: {
peers: info.currentConnectCount,
syncLag: blockInfo.number - solidityInfo.number,
version: info.configNodeInfo?.codeVersion
}
};
} catch (error) {
return {
status: 'unhealthy',
error: error.message
};
}
}
2. Version Compatibility Check
async function checkCompatibility(requiredVersion) {
const info = await getNodeInfo();
const nodeVersion = info.configNodeInfo?.codeVersion || '0.0.0';
return {
compatible: compareVersions(nodeVersion, requiredVersion) >= 0,
nodeVersion,
requiredVersion
};
}
3. Network Statistics
async function getNetworkStats() {
const info = await getNodeInfo();
// Analyze peer versions
const versionStats = {};
info.peerList?.forEach(peer => {
const version = peer.nodeInfo?.codeVersion || 'Unknown';
versionStats[version] = (versionStats[version] || 0) + 1;
});
return {
totalPeers: info.currentConnectCount,
activePeers: info.activeConnectCount,
passivePeers: info.passiveConnectCount,
versionDistribution: versionStats,
networkTraffic: formatBytes(info.totalFlow)
};
}
Best Practices
- Cache Results - Node info can be cached for 30-60 seconds
- Monitor Regularly - Check node health every 1-5 minutes
- Alert Thresholds - Set alerts for low peers or high sync lag
- Version Tracking - Monitor node version for required updates
- Fallback Nodes - Have backup nodes ready if health degrades
Related Methods
- wallet/getchainparameters - Get chain configuration
- wallet/getnowblock - Get latest block
- wallet/listwitnesses - Get witness list
Need help? Contact support or visit our TRON documentation.