This repository has been archived by the owner on Jun 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 455
/
network.js
397 lines (354 loc) · 10.5 KB
/
network.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/*
* Copyright © 2019 Lisk Foundation
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
* no part of this software, including this file, may be copied, modified,
* propagated, or distributed except according to the terms contained in the
* LICENSE file.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
const { getRandomBytes } = require('@liskhq/lisk-cryptography');
const {
P2P,
EVENT_NETWORK_READY,
EVENT_NEW_INBOUND_PEER,
EVENT_CLOSE_INBOUND,
EVENT_CLOSE_OUTBOUND,
EVENT_CONNECT_OUTBOUND,
EVENT_DISCOVERED_PEER,
EVENT_FAILED_TO_FETCH_PEER_INFO,
EVENT_FAILED_TO_PUSH_NODE_INFO,
EVENT_OUTBOUND_SOCKET_ERROR,
EVENT_INBOUND_SOCKET_ERROR,
EVENT_UPDATED_PEER_INFO,
EVENT_FAILED_PEER_INFO_UPDATE,
EVENT_REQUEST_RECEIVED,
EVENT_MESSAGE_RECEIVED,
EVENT_BAN_PEER,
EVENT_UNBAN_PEER,
} = require('@liskhq/lisk-p2p');
const { createLoggerComponent } = require('../../components/logger');
const { createStorageComponent } = require('../../components/storage');
const { lookupPeersIPs } = require('./utils');
const { NetworkInfo } = require('./components/storage/entities');
const hasNamespaceReg = /:/;
const NETWORK_INFO_KEY_NODE_SECRET = 'node_secret';
const NETWORK_INFO_KEY_TRIED_PEERS = 'tried_peers_list';
const DEFAULT_PEER_SAVE_INTERVAL = 10 * 60 * 1000; // 10min in ms
module.exports = class Network {
constructor(options) {
this.options = options;
this.channel = null;
this.logger = null;
this.storage = null;
this.secret = null;
}
async bootstrap(channel) {
this.channel = channel;
const loggerConfig = await this.channel.invoke(
'app:getComponentConfig',
'logger',
);
this.logger = createLoggerComponent({ ...loggerConfig, module: 'network' });
const storageConfig = await this.channel.invoke(
'app:getComponentConfig',
'storage',
);
const dbLogger =
storageConfig.logFileName &&
storageConfig.logFileName === loggerConfig.logFileName
? this.logger
: createLoggerComponent({
...loggerConfig,
logFileName: storageConfig.logFileName,
module: 'network:database',
});
this.storage = createStorageComponent(storageConfig, dbLogger);
this.storage.registerEntity('NetworkInfo', NetworkInfo);
const status = await this.storage.bootstrap();
if (!status) {
throw new Error('Cannot bootstrap the storage component');
}
// Load peers from the database that were tried or connected the last time node was running
const previousPeersStr = await this.storage.entities.NetworkInfo.getKey(
NETWORK_INFO_KEY_TRIED_PEERS,
);
let previousPeers = [];
try {
previousPeers = previousPeersStr ? JSON.parse(previousPeersStr) : [];
} catch (err) {
this.logger.error({ err }, 'Failed to parse JSON of previous peers.');
}
// Get previous secret if exists
const secret = await this.storage.entities.NetworkInfo.getKey(
NETWORK_INFO_KEY_NODE_SECRET,
);
if (!secret) {
this.secret = getRandomBytes(4).readUInt32BE(0);
await this.storage.entities.NetworkInfo.setKey(
NETWORK_INFO_KEY_NODE_SECRET,
this.secret,
);
} else {
this.secret = Number(secret);
}
const sanitizeNodeInfo = nodeInfo => ({
...nodeInfo,
wsPort: this.options.wsPort,
advertiseAddress: this.options.advertiseAddress,
});
const initialNodeInfo = sanitizeNodeInfo(
await this.channel.invoke('app:getApplicationState'),
);
const seedPeers = await lookupPeersIPs(this.options.seedPeers, true);
const blacklistedPeers = this.options.blacklistedPeers || [];
const fixedPeers = this.options.fixedPeers
? this.options.fixedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort,
}))
: [];
const whitelistedPeers = this.options.whitelistedPeers
? this.options.whitelistedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort,
}))
: [];
const p2pConfig = {
nodeInfo: initialNodeInfo,
hostIp: this.options.hostIp,
blacklistedPeers,
fixedPeers,
whitelistedPeers,
seedPeers: seedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort,
})),
previousPeers,
maxOutboundConnections: this.options.maxOutboundConnections,
maxInboundConnections: this.options.maxInboundConnections,
peerBanTime: this.options.peerBanTime,
populatorInterval: this.options.populatorInterval,
sendPeerLimit: this.options.sendPeerLimit,
maxPeerDiscoveryResponseLength: this.options
.maxPeerDiscoveryResponseLength,
maxPeerInfoSize: this.options.maxPeerInfoSize,
wsMaxPayload: this.options.wsMaxPayload,
secret: this.secret,
};
this.p2p = new P2P(p2pConfig);
this.channel.subscribe('app:state:updated', event => {
const newNodeInfo = sanitizeNodeInfo(event.data);
try {
this.p2p.applyNodeInfo(newNodeInfo);
} catch (error) {
this.logger.error(
`Applying NodeInfo failed because of error: ${error.message ||
error}`,
);
}
});
// ---- START: Bind event handlers ----
this.p2p.on(EVENT_NETWORK_READY, () => {
this.logger.debug('Node connected to the network');
this.channel.publish('network:ready');
});
this.p2p.on(EVENT_CLOSE_OUTBOUND, closePacket => {
this.logger.debug(
{
ipAddress: closePacket.peerInfo.ipAddress,
wsPort: closePacket.peerInfo.wsPort,
code: closePacket.code,
reason: closePacket.reason,
},
'EVENT_CLOSE_OUTBOUND: Close outbound peer connection',
);
});
this.p2p.on(EVENT_CLOSE_INBOUND, closePacket => {
this.logger.debug(
{
ipAddress: closePacket.peerInfo.ipAddress,
wsPort: closePacket.peerInfo.wsPort,
code: closePacket.code,
reason: closePacket.reason,
},
'EVENT_CLOSE_INBOUND: Close inbound peer connection',
);
});
this.p2p.on(EVENT_CONNECT_OUTBOUND, peerInfo => {
this.logger.debug(
{
ipAddress: peerInfo.ipAddress,
wsPort: peerInfo.wsPort,
},
'EVENT_CONNECT_OUTBOUND: Outbound peer connection',
);
});
this.p2p.on(EVENT_DISCOVERED_PEER, peerInfo => {
this.logger.trace(
{
ipAddress: peerInfo.ipAddress,
wsPort: peerInfo.wsPort,
},
'EVENT_DISCOVERED_PEER: Discovered peer connection',
);
});
this.p2p.on(EVENT_NEW_INBOUND_PEER, peerInfo => {
this.logger.debug(
{
ipAddress: peerInfo.ipAddress,
wsPort: peerInfo.wsPort,
},
'EVENT_NEW_INBOUND_PEER: Inbound peer connection',
);
});
this.p2p.on(EVENT_FAILED_TO_FETCH_PEER_INFO, error => {
this.logger.error(error.message || error);
});
this.p2p.on(EVENT_FAILED_TO_PUSH_NODE_INFO, error => {
this.logger.trace(error.message || error);
});
this.p2p.on(EVENT_OUTBOUND_SOCKET_ERROR, error => {
this.logger.debug(error.message || error);
});
this.p2p.on(EVENT_INBOUND_SOCKET_ERROR, error => {
this.logger.debug(error.message || error);
});
this.p2p.on(EVENT_UPDATED_PEER_INFO, peerInfo => {
this.logger.trace(
{
ipAddress: peerInfo.ipAddress,
wsPort: peerInfo.wsPort,
},
'EVENT_UPDATED_PEER_INFO: Update peer info',
JSON.stringify(peerInfo),
);
});
this.p2p.on(EVENT_FAILED_PEER_INFO_UPDATE, error => {
this.logger.error(error.message || error);
});
this.p2p.on(EVENT_REQUEST_RECEIVED, async request => {
this.logger.trace(
`EVENT_REQUEST_RECEIVED: Received inbound request for procedure ${request.procedure}`,
);
// If the request has already been handled internally by the P2P library, we ignore.
if (request.wasResponseSent) {
return;
}
const hasTargetModule = hasNamespaceReg.test(request.procedure);
// If the request has no target module, default to chain (to support legacy protocol).
const sanitizedProcedure = hasTargetModule
? request.procedure
: `chain:${request.procedure}`;
try {
const result = await this.channel.invokePublic(sanitizedProcedure, {
data: request.data,
peerId: request.peerId,
});
this.logger.trace(
`Peer request fulfilled event: Responded to peer request ${request.procedure}`,
);
request.end(result); // Send the response back to the peer.
} catch (error) {
this.logger.error(
`Peer request not fulfilled event: Could not respond to peer request ${
request.procedure
} because of error: ${error.message || error}`,
);
request.error(error); // Send an error back to the peer.
}
});
this.p2p.on(EVENT_MESSAGE_RECEIVED, async packet => {
this.logger.trace(
`EVENT_MESSAGE_RECEIVED: Received inbound message from ${packet.peerId} for event ${packet.event}`,
);
this.channel.publish('network:event', packet);
});
this.p2p.on(EVENT_BAN_PEER, peerId => {
this.logger.error(
{ peerId },
'EVENT_MESSAGE_RECEIVED: Peer has been banned temporarily',
);
});
this.p2p.on(EVENT_UNBAN_PEER, peerId => {
this.logger.error(
{ peerId },
'EVENT_MESSAGE_RECEIVED: Peer ban has expired',
);
});
setInterval(async () => {
const triedPeers = this.p2p.getTriedPeers();
if (triedPeers.length) {
await this.storage.entities.NetworkInfo.setKey(
NETWORK_INFO_KEY_TRIED_PEERS,
JSON.stringify(triedPeers),
);
}
}, DEFAULT_PEER_SAVE_INTERVAL);
// ---- END: Bind event handlers ----
try {
await this.p2p.start();
} catch (error) {
this.logger.fatal(
{
message: error.message,
stack: error.stack,
},
'Failed to initialize network',
);
process.emit('cleanup', error);
}
}
get actions() {
return {
request: async action =>
this.p2p.request({
procedure: action.params.procedure,
data: action.params.data,
}),
send: action =>
this.p2p.send({
event: action.params.event,
data: action.params.data,
}),
requestFromPeer: async action =>
this.p2p.requestFromPeer(
{
procedure: action.params.procedure,
data: action.params.data,
},
action.params.peerId,
),
sendToPeer: action =>
this.p2p.sendToPeer(
{
event: action.params.event,
data: action.params.data,
},
action.params.peerId,
),
broadcast: action =>
this.p2p.broadcast({
event: action.params.event,
data: action.params.data,
}),
getConnectedPeers: () => this.p2p.getConnectedPeers(),
getDisconnectedPeers: () => this.p2p.getDisconnectedPeers(),
applyPenalty: action =>
this.p2p.applyPenalty({
peerId: action.params.peerId,
penalty: action.params.penalty,
}),
};
}
async cleanup() {
// TODO: Unsubscribe 'app:state:updated' from channel.
this.logger.info('Cleaning network...');
return this.p2p.stop();
}
};