Last active
January 6, 2019 21:27
-
-
Save tonyofbyteball/99b5e5001dc81ed296a0525d5eb38cde to your computer and use it in GitHub Desktop.
Provably fair algorithm of selecting the winner based on bitcoin hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// bitcoin_hash is the hash (in hex) of the latest Bitcoin block | |
// arrPoints is array of points of all addresses ordered by address [{address: "...", points: 1234}, ...] | |
// rows1 is array of balances of all addresses ordered by address [{address: "...", balance: 1234}, ...] | |
// sum is the sum of all points | |
// 1. winner by points | |
let hash = crypto.createHash('sha256').update(bitcoin_hash).digest('hex'); | |
let number = new BigNumber(hash, 16); | |
let random = (number.div(new BigNumber(2).pow(256))).times(sum); | |
let sum2 = new BigNumber(0); | |
let winner_address; | |
for (let i = 0; i < arrPoints.length; i++) { | |
sum2 = sum2.add(arrPoints[i].points); | |
if (random.lte(sum2)) { | |
winner_address = arrPoints[i].address; | |
break; | |
} | |
} | |
// 2. winner by balances | |
let bal_hash = crypto.createHash('sha256').update(hash).digest('hex'); | |
let bal_number = new BigNumber(bal_hash, 16); | |
let bal_random = (bal_number.div(new BigNumber(2).pow(256))).times(sum_balances); | |
let bal_sum2 = 0; | |
let balance_winner_address; | |
for (let i = 0; i < rows1.length; i++) { | |
bal_sum2 += rows1[i].balance; | |
if (bal_random.lte(bal_sum2)) { | |
balance_winner_address = rows1[i].address; | |
break; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment