@derin-n/provablyfair
Version:
A provably fair algorithm
58 lines (52 loc) • 2.08 kB
JavaScript
//you will need to generate your own host seed, you can generate it via the method below
//generate one seed, one of them will be your host seed, hold onto it
//the game hash will be created in the browser and sent to the server
const generateRandomSeed = function (callback) {
//randomly generate 1000 bytes of data
crypto.randomBytes(1000, (err, randomData) => {
if (err) throw err;
//define hasher
let hashedSeed = crypto.createHash("sha512");
//convert the data to string and hash it
hashedSeed.update(randomData.toString('hex'));
//digest the hash into a string
let digestSeed = hashedSeed.digest('hex');
callback(digestSeed);
});
}
//generate results from hashes
//for example, get the game seed from the client with a socket, and pass it to this function
const generateResult = function (hostSeed, gameSeed, callback) {
//create hasher
let combinedHash = crypto.createHash('sha512');
//combine the host seed with the game seed
let concatHash = hostSeed + gameSeed;
//hash the combination
combinedHash.update(concatHash);
//digest the hash into a string
let combinedHashHex = combinedHash.digest('hex');
//define result
let result = "";
//result will be converted into numbers
let numberResult;
//for every char in the string
for (let i = 0; i < combinedHashHex.length; i++) {
//get the char
let singleChar = combinedHashHex.charAt(i);
//check if number and result has less than 2 number chars
if (!(isNaN(singleChar)) && result.length < 2) {
//turn char into number
numberChar = parseInt(singleChar);
//add the char to result
result += singleChar;
}
//when result has two numbers, the first one can be zero
if (result.length == 2) {
//convert into number
numberResult = parseInt(result);
//callback with the numerical result
callback(numberResult);
return;
}
}
}