Code snippet to check which Hive nodes are healthy

in #hive9 months ago (edited)

Here is a Javascript script that allows you to verify which HIVE nodes are healthy.

A modified version of this code can be added in a website to switch to a different node when the one in use stops being healthy.
It can also be tested locally using NodeJs.

How to test this code snippet in a browser:

  • Open your favorite browser (I strongly recommend using Brave browser for its speed and security)

  • Navigate to https://cdn.jsdelivr.net/npm/steem/dist/steem.min.js (SteemJs)

  • On that page open the DevTools (Ctrl + Shift + J on Linux/Windows and Cmd + Opt + J on Mac)

  • Copy & paste (Ctrl + A and Ctrl + C) the steem.js code displayed on that page into the Browser Console and press enter.

  • Copy & paste my script below into the Console

  • Press enter.


Code snippet:

// To execute this script in NodeJs, simply add the next 2 lines:
// const steem = require('steem');
// const fetch = require('node-fetch');

steem.config.set('address_prefix', 'STM');
steem.config.set('chain_id', '0000000000000000000000000000000000000000000000000000000000000000');

var nodes = [
  'https://api.hive.blog', // (hive)
  'https://api.pharesim.me',
  'https://steemd.minnowsupportproject.org', // (steem)
  'https://api.steemit.com', // (steem)
  'https://anyx.io', // (hive)
  'https://api.hivekings.com', // (hive)
  'https://api.steemitdev.com', // (steem)
  'https://steemd.privex.io', // (steem)
  'https://api.openhive.network', // (hive)
];

var setWorkingNode = id => new Promise((resolve) => {
  const currentNode = nodes[id];
  fetch(currentNode)
    .then(resp => resp.json())
    .then((json) => {
      if (json.status !== 'OK' || json.error) {
        console.error(`Node ${currentNode} not OK. ${JSON.stringify(json, null, 2)}`);
        resolve({ ok: false });
      } else {
        steem.api.setOptions({ url: currentNode });
        resolve({ ok: true });
      }
    })
    .catch((err) => {
      console.error(`Error checking ${currentNode} node state. ${err}`);
      resolve({ ok: false });
    });
});

var confirmHiveResponse = () => new Promise((resolve) => {
  steem.api.getAccounts(
    ['gaottantacinque'],
    (err, response) => {
      if (err) {
        console.error(`Unable to confirm HIVE network. ${err}`);
        resolve(false);
        return;
      }
      const { balance = ' ' } = response[0];
      const [_, currency] = balance.split(' ');
      resolve(currency === 'HIVE');
    },
  );
});

var startChecks = async () => {
  const healthyNodes = [];
  for (let id = 0; id < nodes.length; id++) {
    const currentNode = nodes[id];
    console.log(`>> Checking node ${currentNode}`);
    const { ok } = await setWorkingNode(id);
    console.log(`${ok ? 'Connected' : 'Unable to connect'} to ${currentNode}.`);
    if (ok) {
      const isHive = await confirmHiveResponse();
      console.log(`Confirmed that it uses HIVE: ${isHive}`);
      if (isHive) healthyNodes.push(currentNode);
    }
  }
  console.log(`Healthy HIVE nodes: ${JSON.stringify(healthyNodes, null, 2)}`);
};
startChecks();


Outcome:

image.png

Sort:  

I recommend checking get_config to check which chain you're on:

https://developers.steem.io/apidefinitions/#database_api.get_config vs. https://developers.hive.io/apidefinitions/#database_api.get_config

Using get_config will yield fields either starting with STEEM_ or HIVE_.

Thanks, giving that a try.

  1. Curl:
    curl -s --data '{"jsonrpc":"2.0", "method":"database_api.get_config", "id":1}' https://api.openhive.network

  2. Fetch:
    fetch("https://api.openhive.network", {
      body: '{"jsonrpc":"2.0", "method":"database_api.get_config", "id":1}',
      headers: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST"
    }).then(resp => resp.json()).then(console.log);

Nice 👍. Will give it a try/read later.

Nice... Just tried it... any recommendations for crazy useful UIs JS consoles? I am thinking on something like JypiterHub Playbooks kind of thing.

I haven’t played withJypiterHub before but for simple JS consoles/UIs I would recommend jsfiddle, jsbin, codepen and similar online playgrounds.

Thanks... will put those in bucket list to check. Weekend approaching... and sounds like I am going to be busy :S

!discovery 30


Questo post è stato condiviso e votato all'interno del discord del team curatori di discovery-it Entra nella nostra community! hive-193212
This post was shared and voted inside the discord by the curators team of discovery-it. Join our community! hive-193212


Just now discovering your blog. You should post or cross-post some of your content to HiveDevs community sometimes. You deserve more recognition.

Thanks, I will follow your advice! =}