forked from ZENZO-Ecosystem/Node-Monitor
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
68 lines (56 loc) · 1.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/* Setup initial NPM packages */
const RPC_CLIENT = require('bitcoin-rpc-promise')
const express = require('express')
const app = express()
require('dotenv').config()
/* Declare local variables */
const auth = {
user: process.env.rpcuser,
pass: process.env.rpcpassword,
host: "localhost", /* Default Recommended */
port: 9796
}
let node = {
status: "offline",
blocks: 0,
peers: 0
}
/* Initialize RPC connection */
const RPC = new RPC_CLIENT('http://' + auth.user + ':' + auth.pass + '@' + auth.host + ':' + auth.port)
/* Initialize express server */
app.get('/health', function (req, res) {
res.json(node)
})
app.listen(3000)
/* Fired repeatedly while the node is Offline or Errored, in an attempt to reconnect and verify node health */
function checkRPC () {
RPC.call('getblockcount').then(blocks => {
node.status = "online"
console.log("RPC Response: " + blocks + ", Node status changed to " + node.status)
updateRPC()
}).catch(rpcError)
}
checkRPC()
/* Fired repeatedly, updates node information periodically, if online */
function updateRPC () {
if (node.status === "online") {
RPC.call('getblockcount').then(blocks => {
node.blocks = blocks
RPC.call('getconnectioncount').then(conns => {
node.peers = conns
console.log("RPC Updated: " + blocks + " blocks and " + conns + " peers")
}).catch(rpcError)
}).catch(rpcError)
}
}
setInterval(updateRPC, sec(10))
/* Fired when the Monitor catches an RPC error */
function rpcError () {
node.status = "offline"
console.error("RPC Error: Node status changed to " + node.status)
setTimeout(checkRPC, sec(60))
}
/* Converts seconds into miliseconds */
function sec (s) {
return s * 1000
}