|
| 1 | +const WebSocket = require("ws"); |
| 2 | +const http = require("http"); |
| 3 | +const https = require("https"); |
| 4 | + |
| 5 | +const LIVENESS_CHECK=`{"jsonrpc":"2.0","method":"web3_clientVersion","params":[],"id":42}`; |
| 6 | + |
| 7 | +const parseAndRespond = (data, cb) => { |
| 8 | + let resp; |
| 9 | + try { |
| 10 | + resp = JSON.parse(data); |
| 11 | + if (resp.error) { |
| 12 | + return cb(resp.error); |
| 13 | + } |
| 14 | + } catch (e) { |
| 15 | + return cb('Version data is not valid JSON'); |
| 16 | + } |
| 17 | + if (!resp || !resp.result) { |
| 18 | + return cb('No version returned'); |
| 19 | + } |
| 20 | + const [_, version, __] = resp.result.split('/'); |
| 21 | + cb(null, version); |
| 22 | +}; |
| 23 | + |
| 24 | +const testRpcWithEndpoint = (endpoint, cb) => { |
| 25 | + const options = { |
| 26 | + method: "POST", |
| 27 | + timeout: 1000, |
| 28 | + headers: { |
| 29 | + "Content-Type": "application/json", |
| 30 | + "Content-Length": Buffer.byteLength(LIVENESS_CHECK) |
| 31 | + } |
| 32 | + }; |
| 33 | + |
| 34 | + let obj = http; |
| 35 | + if (endpoint.startsWith('https')) { |
| 36 | + obj = https; |
| 37 | + } |
| 38 | + |
| 39 | + const req = obj.request(endpoint, options, (res) => { |
| 40 | + let data = ""; |
| 41 | + res.on("data", chunk => { data += chunk; }); |
| 42 | + res.on("end", () => parseAndRespond(data, cb)); |
| 43 | + }); |
| 44 | + req.on("error", (e) => cb(e)); |
| 45 | + req.write(LIVENESS_CHECK); |
| 46 | + req.end(); |
| 47 | +}; |
| 48 | + |
| 49 | +const testWsEndpoint = (endpoint, cb) => { |
| 50 | + const conn = new WebSocket(endpoint); |
| 51 | + conn.on("message", (data) => { |
| 52 | + parseAndRespond(data, cb); |
| 53 | + conn.close(); |
| 54 | + }); |
| 55 | + conn.on("open", () => conn.send(LIVENESS_CHECK)); |
| 56 | + conn.on("error", (e) => cb(e)); |
| 57 | +}; |
| 58 | + |
| 59 | +module.exports = { |
| 60 | + testWsEndpoint, |
| 61 | + testRpcWithEndpoint |
| 62 | +}; |
0 commit comments