-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
100 lines (86 loc) · 2.39 KB
/
Copy pathserver.js
File metadata and controls
100 lines (86 loc) · 2.39 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
const express = require('express');
const axios = require('axios');
const WebSocket = require('ws');
const NodeCache = require('node-cache');
const fs = require('fs');
const path = require('path');
const app = express();
const cache = new NodeCache({ stdTTL: 60 });
const PORT = 3000;
const jsonFilePath = path.join(__dirname, 'servers-electrumx.json');
let servers = [];
try {
const fileContent = fs.readFileSync(jsonFilePath, 'utf8');
const jsonData = JSON.parse(fileContent);
if (jsonData.servers && Array.isArray(jsonData.servers)) {
servers = jsonData.servers;
} else {
console.error('Invalid format in servers-electrumx.json');
}
} catch (error) {
console.error('Error reading the file servers-electrumx.json:', error.message);
}
const checkServers = async () => {
if (servers.length === 0) {
return [{ error: 'No servers available for checking' }];
}
const results = await Promise.all(
servers.map(server => new Promise((resolve) => {
const ws = new WebSocket(server);
ws.on('open', () => {
ws.send(JSON.stringify({
id: 1,
method: 'blockchain.headers.subscribe',
params: []
}));
});
ws.on('message', (data) => {
const response = JSON.parse(data);
if (response.id === 1 && response.result) {
resolve({
server,
block_height: response.result.height,
status: 'online',
last_checked: new Date().toISOString()
});
} else {
resolve({
server,
block_height: null,
status: 'error',
last_checked: new Date().toISOString()
});
}
ws.close();
});
ws.on('error', () => {
resolve({
server,
block_height: null,
status: 'offline',
last_checked: new Date().toISOString()
});
});
ws.on('close', () => {
resolve({
server,
block_height: null,
status: 'offline',
last_checked: new Date().toISOString()
});
});
}))
);
return results;
};
app.get('/api/electrumx', async (req, res) => {
let status = cache.get('status');
if (!status) {
status = await checkServers();
cache.set('status', status);
}
res.json(status);
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});