-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeers.js
95 lines (85 loc) · 2.37 KB
/
peers.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
/*
* 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 MAX_PEERS = 100;
/**
* Main peers methods. Initializes library with scope content.
*
* @class
* @memberof modules
* @see Parent: {@link chain}
* @param {scope} scope - App instance
*/
class Peers {
constructor({ channel, forgingForce, minBroadhashConsensus }) {
this.forgingForce = forgingForce;
this.channel = channel;
this.minBroadhashConsensus = minBroadhashConsensus;
this.broadhashConsensusCalculationInterval = 5000;
}
/**
* Returns consensus calculated by calculateConsensus.
*
* @returns {number|undefined} Last calculated consensus or null if wasn't calculated yet
*/
async getLastConsensus(broadhash) {
return this.calculateConsensus(broadhash);
}
/**
* Calculates consensus for as a ratio active to matched peers.
*
* @returns {Promise.<number, Error>} Consensus or undefined if forgingForce = true
*/
// eslint-disable-next-line class-methods-use-this
async calculateConsensus() {
const { broadhash } = await this.channel.invoke('app:getApplicationState');
const activeCount = Math.min(
await this.channel.invoke(
'network:getUniqueOutboundConnectedPeersCount',
{},
),
MAX_PEERS,
);
const matchedCount = Math.min(
await this.channel.invoke(
'network:getUniqueOutboundConnectedPeersCount',
{
broadhash,
},
),
MAX_PEERS,
);
const consensus = +((matchedCount / activeCount) * 100).toPrecision(2);
return Number.isNaN(consensus) ? 0 : consensus;
}
// Public methods
/**
* Returns true if application consensus is less than MIN_BROADHASH_CONSENSUS.
* Returns false if forgingForce is true.
*
* @returns {boolean}
* @todo Add description for the return value
*/
async isPoorConsensus(broadhash) {
if (this.forgingForce) {
return false;
}
const consensus = await this.calculateConsensus(broadhash);
return consensus < this.minBroadhashConsensus;
}
}
// Export
module.exports = {
Peers,
};