Skip to content

Commit

Permalink
Fixed random bias.
Browse files Browse the repository at this point in the history
  • Loading branch information
Ylianst committed Feb 9, 2021
1 parent f7300b8 commit 956fdd8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
10 changes: 8 additions & 2 deletions common.js
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,14 @@ module.exports.data2blob = function (data) {
return blob;
};

// Generate random numbers
module.exports.random = function (max) { (require('crypto').randomBytes(4).readUInt32BE(0) % max); };
// Generate random numbers between 0 and max without bias.
module.exports.random = function (max) {
const crypto = require('crypto');
var maxmask = 1, r;
while (maxmask < max) { maxmask = (maxmask << 1) + 1; }
do { r = (crypto.randomBytes(4).readUInt32BE(0) & maxmask); } while (r > max);
return r;
};

// Split a comma seperated string, ignoring commas in quotes.
module.exports.quoteSplit = function (str) {
Expand Down
3 changes: 2 additions & 1 deletion multiserver.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ module.exports.CreateMultiServer = function (parent, args) {

// Get the next retry time in milliseconds
function getConnectRetryTime() {
if (obj.retryBackoff < 30000) { obj.retryBackoff += ((require('crypto').randomBytes(4).readUInt32BE(0) % 3000) + 1000); }
// The (random & 0x1FFF) creates a random number between 0 and 4096.
if (obj.retryBackoff < 30000) { obj.retryBackoff += ((require('crypto').randomBytes(4).readUInt32BE(0) & 0x1FFF) + 1000); }
return obj.retryBackoff;
}

Expand Down

0 comments on commit 956fdd8

Please sign in to comment.