forked from Leasehold/leasehold-net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
445 lines (398 loc) · 13.5 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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
const crypto = require('crypto');
const { lookupPeersIPs, filterByParams, consolidatePeers } = require('./utils');
const util = require('util');
const fs = require('fs');
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
const path = require('path');
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('lp2p');
const DEFAULT_PEER_SAVE_INTERVAL = 10 * 60 * 1000; // 10 mins in ms
const DEFAULT_PEER_LIST_FILE_PATH = path.resolve(__dirname, 'peers.json');
const MAX_CHANNEL_NAME_LENGTH = 200;
const DEFAULT_MODULE_ALIAS = 'capitalisk_net';
const hasNamespaceReg = /:/;
class CapitaliskNet {
constructor({alias, logger, config}) {
this.options = config;
this.alias = alias || DEFAULT_MODULE_ALIAS;
this.logger = logger;
this.channel = null;
this.secret = null;
}
get dependencies() {
return ['app'];
}
get events() {
return ['event'];
}
get actions() {
return {
request: {
handler: async action => {
return this.p2p.request({
procedure: action.params.procedure,
data: action.params.data
});
}
},
emit: {
handler: action => {
return this.p2p.send({
event: action.params.event,
data: action.params.data
}, action.params.peerLimit);
}
},
requestFromPeer: {
handler: async action => {
return this.p2p.requestFromPeer(
{
procedure: action.params.procedure,
data: action.params.data,
},
action.params.peerId
);
}
},
emitToPeer: {
handler: action => {
return this.p2p.sendToPeer(
{
event: action.params.event,
data: action.params.data,
},
action.params.peerId
);
}
},
getPeers: {
handler: action => {
let peers = consolidatePeers({
connectedPeers: this.p2p.getConnectedPeers(),
disconnectedPeers: this.p2p.getDisconnectedPeers()
});
return filterByParams(peers, action.params);
}
},
getConnectedPeers: {
handler: action => {
let peers = consolidatePeers({
connectedPeers: this.p2p.getConnectedPeers()
});
return filterByParams(peers, action.params);
}
},
getPeersCount: {
handler: action => {
let peers = consolidatePeers({
connectedPeers: this.p2p.getConnectedPeers(),
disconnectedPeers: this.p2p.getDisconnectedPeers()
});
let { limit, offset, ...filterWithoutLimitOffset } = action.params;
return filterByParams(peers, filterWithoutLimitOffset).length;
}
},
getUniqueOutboundConnectedPeersCount: {
handler: action => {
let peers = consolidatePeers({
connectedPeers: this.p2p.getUniqueOutboundConnectedPeers()
});
let { limit, offset, ...filterWithoutLimitOffset } = action.params;
return filterByParams(peers, filterWithoutLimitOffset).length;
}
},
applyPenalty: {
handler: action => {
return this.p2p.applyPenalty(action.params.peerId, action.params.penalty);
}
}
};
}
async load(channel) {
this.channel = channel;
if (this.options.peerSelectionPluginPath) {
this.logger.debug(
`Using peer selection plugin at path ${this.options.peerSelectionPluginPath} relative to the current working directory`
);
let peerSelectionPlugin = require(path.resolve(this.options.peerSelectionPluginPath));
this.peerSelectionForConnection = peerSelectionPlugin.peerSelectionForConnection;
this.peerSelectionForRequest = peerSelectionPlugin.peerSelectionForRequest;
this.peerSelectionForSend = peerSelectionPlugin.peerSelectionForSend;
} else {
this.logger.debug(
`Using default peer selection`
);
}
let peerListFilePath = this.options.peerListFilePath == null ?
DEFAULT_PEER_LIST_FILE_PATH : path.resolve(this.options.peerListFilePath);
// Load peers from the database that were tried or connected the last time node was running
let previousPeersStr;
try {
previousPeersStr = await readFile(peerListFilePath, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
this.logger.debug(`No existing peer list file found at ${peerListFilePath}`);
} else {
this.logger.error(`Failed to read file ${peerListFilePath} - ${err.message}`);
}
}
let previousPeers = [];
try {
previousPeers = previousPeersStr ? JSON.parse(previousPeersStr) : [];
} catch (err) {
this.logger.error(`Failed to parse JSON of previous peers - ${err.message}`);
}
this.secret = crypto.randomBytes(4).readUInt32BE(0);
let sanitizeNodeInfo = nodeInfo => ({
...nodeInfo,
wsPort: this.options.wsPort
});
let initialNodeInfo = sanitizeNodeInfo(
await this.channel.invoke('app:getApplicationState')
);
let seedPeers = await lookupPeersIPs(this.options.seedPeers, true);
let blacklistedIPs = this.options.blacklistedIPs || [];
let fixedPeers = this.options.fixedPeers
? this.options.fixedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort
}))
: [];
let whitelistedPeers = this.options.whitelistedPeers
? this.options.whitelistedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort
}))
: [];
let p2pConfig = {
nodeInfo: initialNodeInfo,
hostIp: this.options.hostIp,
blacklistedIPs,
fixedPeers,
whitelistedPeers,
seedPeers: seedPeers.map(peer => ({
ipAddress: peer.ip,
wsPort: peer.wsPort
})),
previousPeers,
connectTimeout: this.options.connectTimeout,
ackTimeout: this.options.ackTimeout,
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,
outboundShuffleInterval: this.options.outboundShuffleInterval,
netgroupProtectionRatio: this.options.netgroupProtectionRatio,
latencyProtectionRatio: this.options.latencyProtectionRatio,
productivityProtectionRatio: this.options.productivityProtectionRatio,
longevityProtectionRatio: this.options.longevityProtectionRatio,
wsMaxPayloadInbound: this.options.wsMaxPayloadInbound,
wsMaxPayloadOutbound: this.options.wsMaxPayloadOutbound,
wsMaxMessageRate: this.options.wsMaxMessageRate,
wsMaxMessageRatePenalty: this.options.wsMaxMessageRatePenalty,
rateCalculationInterval: this.options.rateCalculationInterval,
secret: this.secret
};
if (this.peerSelectionForConnection) {
p2pConfig.peerSelectionForConnection = this.peerSelectionForConnection;
}
if (this.peerSelectionForRequest) {
p2pConfig.peerSelectionForRequest = this.peerSelectionForRequest;
}
if (this.peerSelectionForSend) {
p2pConfig.peerSelectionForSend = this.peerSelectionForSend;
}
this.p2p = new P2P(p2pConfig);
this.channel.subscribe('app:state:updated', event => {
let newNodeInfo = sanitizeNodeInfo(event.data);
try {
this.p2p.applyNodeInfo(newNodeInfo);
} catch (error) {
this.logger.error(
`Applying NodeInfo failed because of error: ${error.message ||
error}`
);
}
});
this.p2p.on(EVENT_NETWORK_READY, () => {
this.logger.debug('Node connected to the network');
this.channel.publish(`${this.alias}: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;
}
let hasTargetModule = hasNamespaceReg.test(request.procedure);
// If the request has no target module, default to chain (to support legacy protocol).
let sanitizedProcedure = hasTargetModule
? request.procedure
: `chain:${request.procedure}`;
try {
let result = await this.channel.invokePublic(sanitizedProcedure, 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}`
);
let targetChannelName = `${this.alias}:event:${packet.event}`;
if (targetChannelName.length > MAX_CHANNEL_NAME_LENGTH) {
this.logger.error(
`Peer ${packet.peerId} tried to publish data to a custom channel name which exceeded the max length of ${MAX_CHANNEL_NAME_LENGTH}`
);
} else {
this.channel.publish(targetChannelName, packet.data, {peerId: packet.peerId});
}
// For backward compatibility with Lisk chain module.
this.channel.publish(`${this.alias}:event`, packet);
});
this.p2p.on(EVENT_BAN_PEER, peerId => {
this.logger.error(
{ peerId },
'EVENT_BAN_PEER: Peer has been banned temporarily'
);
});
this.p2p.on(EVENT_UNBAN_PEER, peerId => {
this.logger.error(
{ peerId },
'EVENT_UNBAN_PEER: Peer ban has expired'
);
});
setInterval(async () => {
let peersToSave = this.p2p.getConnectedPeers();
if (peersToSave.length) {
let peersString = JSON.stringify(peersToSave);
await writeFile(peerListFilePath, peersString);
}
}, DEFAULT_PEER_SAVE_INTERVAL);
try {
await this.p2p.start();
} catch (error) {
this.logger.fatal(
{
message: error.message,
stack: error.stack,
},
`Failed to initialize net module`
);
process.emit('cleanup', error);
}
}
async unload() {
this.logger.info(`Stopping net module...`);
return this.p2p.stop();
}
};
module.exports = CapitaliskNet;