Skip to content

Instantly share code, notes, and snippets.

@playflinch
Last active January 30, 2017 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save playflinch/e9cfdb67c0ee89a18d8f290f98457f98 to your computer and use it in GitHub Desktop.
Save playflinch/e9cfdb67c0ee89a18d8f290f98457f98 to your computer and use it in GitHub Desktop.
flinch.io game result calculation
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"math"
"math/big"
)
// GameResult calculates the corresponding crash point for a game hash and salt.
//
// Crash points have two decimal places, so a result of 1234 is interpreted as
// 12.34x. The largest possible result is 6966505673588736.
func GameResult(seed, salt []byte) uint64 {
const nBits = 46 // number of most significant bits to use
// 1. HMAC_SHA256(key=salt, message=seed)
hmacHash := hmac.New(sha256.New, salt)
hmacHash.Write(seed)
seed = hmacHash.Sum(nil)
// 2. r = 46 most significant bits
seedInt := new(big.Int).SetBytes(seed)
seedInt.Rsh(seedInt, sha256.Size*8-nBits)
r := seedInt.Uint64()
// 3. X = r / 2^46
X := float64(r) / math.Pow(2, 46) // uniformly distributed in [0; 1)
// 4. X = 99 / (1-X)
X = 99 / (1 - X)
// 5. return max(trunc(X), 100)
result := uint64(X)
if result == 99 {
return 100
}
return result
}
const { createHmac } = require("crypto")
// gameResult calculates the corresponding crash point for a game hash and salt.
//
// Crash points have two decimal places, so a result of 1234 is interpreted as
// 12.34x. The largest possible result is 6966505673588736.
function gameResult(seed, salt) {
const nBits = 46 // number of most significant bits to use
// 1. HMAC_SHA256(key=salt, message=seed)
const hmac = createHmac("sha256", salt)
hmac.update(seed)
seed = hmac.digest()
// 2. r = 46 most significant bits
seed = seed.readUIntBE(0, 6).toString(2)
while (seed.length < 48) {
seed = '0' + seed
}
seed = seed.substr(0, 46)
const r = parseInt(seed, 2)
// 3. X = r / 2^46
let X = r / Math.pow(2, 46) // uniformly distributed in [0; 1)
// 4. X = 99 / (1-X)
X = 99 / (1 - X)
// 5. return max(trunc(X), 100)
const result = Math.floor(X)
if (result === 99) {
return 100
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment