-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
executable file
·230 lines (196 loc) · 6.28 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
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
let WebSocketServer = require('websocket').server
let WebSocketClient = require('websocket').client
let http = require('http')
let server
const messageSizeLimit = 150 * 1024 * 1024
const frameSizeLimit = 150 * 1024 * 1024
const headersTimeout = process.env.HEADERS_TIMEOUT*1000 || 180000
const log = function (msg, type, logging) {
// Only log if logging is true
if (logging !== true) {
return
}
if (type === "log") {
console.log(msg)
} else if (type === "error") {
console.error(msg)
}
}
// Helper function to convert text or binary to a JSON string
const getMessageData = (message) => {
switch (message.type) {
case "utf8":
return message.utf8Data
case "binary":
return message.binaryData.toString()
}
return "{}"
}
exports.start = function (passed_endpoints, logging) {
let endpoints = []
// If being stared from the commandline, use argv inputs and set logging to true
if (passed_endpoints === undefined) {
logging = true
if (process.argv.length <= 2) {
log('No endpoints provided', 'error', logging)
process.exit()
}
for (let i = 2; i < process.argv.length; i++) {
log('Adding endpoint ' + process.argv[i] + ' to list', 'log', logging)
endpoints.push({
url: process.argv[i],
offlineSince: null,
lastHeader: null,
expectedClose: false
})
}
} else {
for (let i = 0; i < passed_endpoints.length; i++) {
log('Adding endpoint ' + process.argv[i] + ' to list', 'log', logging)
endpoints.push({
url: passed_endpoints[i],
offlineSince: null,
lastHeader: null,
expectedClose: false
})
}
}
server = http.createServer(function () {
})
server.listen(4000, function () {
log('Server is listening on port :4000', 'log', logging)
})
let wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: true,
keepalive: false, // Disable due to bug in CL node
maxReceivedFrameSize: frameSizeLimit,
maxReceivedMessageSize: messageSizeLimit,
})
const selectEndpoint = () => {
if (endpoints.length === 0) return null
if (endpoints.length === 1) return 0
for (let i = 0; i < endpoints.length; i++) {
if (endpoints[i].offlineSince === null) return i
}
let oldestCheck = 0
for (let i = 1; i < endpoints.length; i++) {
if (endpoints[i].offlineSince < endpoints[oldestCheck].offlineSince) {
oldestCheck = i
}
}
endpoints[oldestCheck].offlineSince = null
return oldestCheck
}
const incomingConnection = (connection) => {
log('Accepted incoming connection', 'log', logging)
let client = new WebSocketClient({
maxReceivedFrameSize: frameSizeLimit,
maxReceivedMessageSize: messageSizeLimit,
})
let eth = null
let backlog = []
connection.on('message', function (message) {
if (eth == null) {
backlog.push(message)
return
}
sendData(eth, message)
})
let endpointId = selectEndpoint()
if (endpointId == null) {
log('RPC Error: No suitable endpoints available', 'log', logging)
close(connection)
}
let connected = false
client.on('connect', (ethConnection) => {
connected = true
eth = ethConnection
outgoingConnection(connection, ethConnection, endpointId, backlog)
})
client.on('connectFailed', () => {
log('RPC Error: Unable to connect to endpoint ' + endpoints[endpointId].url, 'log', logging)
endpoints[endpointId].offlineSince = new Date()
close(connection)
})
client.connect(endpoints[endpointId].url, null)
connection.on('close', () => {
endpoints[endpointId].expectedClose = true
close(eth)
log('Disconnecting...', 'log', logging)
})
setTimeout(() => {
if (connected) return
log('RPC Error: Timed out trying to connect to endpoint ' + endpoints[endpointId].url, 'log', logging)
endpoints[endpointId].offlineSince = new Date()
close(connection)
close(eth)
client.abort()
}, 5000)
}
const hasBlockHeaderNotification = (data) => {
let msg = JSON.parse(getMessageData(data))
if (Array.isArray(msg)) {
for (let i = 0; i < msg.length; i++) {
if (isBhn(msg[i])) return true
}
return false
}
return isBhn(msg)
}
const isBhn = (msg) => {
if (!('method' in msg)) return false
if (msg.method !== "eth_subscription") return false
if (!('result' in msg.params)) return false
return ('difficulty' in msg.params.result && 'parentHash' in msg.params.result)
}
const outgoingConnection = (connection, eth, endpointId, backlog) => {
log('Connected to endpoint ' + endpoints[endpointId].url, 'log', logging)
for (let i = 0; i < backlog.length; i++) {
sendData(eth, backlog[i])
}
let intervalId = setInterval(() => {
if (new Date() - endpoints[endpointId].lastHeader > headersTimeout) {
endpoints[endpointId].offlineSince = new Date()
endpoints[endpointId].expectedClose = true
log('RPC Error: Its been too long since we received a block header from ' + endpoints[endpointId].url, 'log', logging)
close(connection)
close(eth)
}
}, 60000)
eth.on('close', () => {
if (!endpoints[endpointId].expectedClose) {
endpoints[endpointId].offlineSince = new Date()
log('RPC Error: Lost connection to endpoint ' + endpoints[endpointId].url + '!', 'log', logging)
}
clearInterval(intervalId)
close(connection)
})
eth.on('message', (message) => {
sendData(connection, message)
if (hasBlockHeaderNotification(message)) {
endpoints[endpointId].lastHeader = new Date()
}
})
}
wsServer.on('connect', incomingConnection)
const close = (connection) => {
if (connection == null || !connection.connected) return
connection.close()
}
const sendData = (connection, data) => {
if (connection == null || !connection.connected) return
connection.send(getMessageData(data))
}
process.on('SIGTERM', () => {
log('Received SIGTERM. Terminating...', 'log', logging)
wsServer.closeAllConnections()
process.exit()
});
}
exports.close = function () {
server.close()
}
if (module.id === require.main.id) {
exports.start()
}