Skip to content
This repository has been archived by the owner on Jun 11, 2024. It is now read-only.

Refactor Peers.prototype.getConsensus - Subtask #1008 #1021

Merged
merged 3 commits into from
Nov 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion logic/broadcaster.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ Broadcaster.prototype.getPeers = function (params, cb) {
}

if (self.consensus !== undefined && originalLimit === constants.maxPeers) {
self.consensus = modules.peers.getConsensus(null, peers);
self.consensus = modules.peers.getConsensus(peers);
library.logger.info(['Broadhash consensus now', self.consensus, '%'].join(' '));
}

Expand Down
33 changes: 16 additions & 17 deletions modules/peers.js
Original file line number Diff line number Diff line change
Expand Up @@ -305,29 +305,28 @@ __private.dbSave = function (cb) {
});
};

Peers.prototype.getConsensus = function (matched, active) {

/**
* Calculates consensus for as a ratio active to matched peers.
* @param {Array<Peer>} active - Active peers (with connected state).
* @param {Array<Peer>} matched - Peers with same as system broadhash.
* @returns {number|undefined} - Consensus or undefined if config.forging.force = true.
*/
Peers.prototype.getConsensus = function (active, matched) {
if (library.config.forging.force) {
return undefined;
}

active = active || __private.getByFilter({state: Peer.STATE.CONNECTED, normalized: false});
matched = matched || __private.getMatched({broadhash: modules.system.getBroadhash()}, active);

active = active.slice(0, constants.maxPeers);
matched = matched.slice(0, constants.maxPeers);

var consensus = Math.round(matched.length / active.length * 100 * 1e2) / 100;

if (isNaN(consensus)) {
return 0;
}

return consensus;
active = active || library.logic.peers.list(true);
var broadhash = modules.system.getBroadhash();
matched = matched || active.filter(function (peer) {
return peer.broadhash === broadhash;
});
var activeCount = Math.min(active.length, constants.maxPeers);
var matchedCount = Math.min(matched.length, activeCount);
var consensus = +(matchedCount / activeCount * 100).toPrecision(2);
return isNaN(consensus) ? 0 : consensus;
};

// Public methods

/**
* Updates peer in peers list.
* @param {peer} peer
Expand Down