Skip to content

Instantly share code, notes, and snippets.

@yoseplee
Last active April 16, 2020 11:16
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 yoseplee/d08d51ec07058365dc4e561ec81854d3 to your computer and use it in GitHub Desktop.
Save yoseplee/d08d51ec07058365dc4e561ec81854d3 to your computer and use it in GitHub Desktop.
a simple cryptographic sortition
package sortition
import (
"log"
"math/big"
)
const sortitionThreshold float64 = 0.3
//Sortition returns true/false decide by threshold which is const value
func Sortition(ratio float64) bool {
if ratio > sortitionThreshold {
return false
}
return true
}
//GetRatioFromHash calculates a float number between [0, 1] with a random hash value which generated by vrf
func GetRatioFromHash(vrfOutput []byte) float64 {
t := &big.Int{}
t.SetBytes(vrfOutput[:])
precision := uint(8 * (len(vrfOutput) + 1))
max, b, err := big.ParseFloat("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", 0, precision, big.ToNearestEven)
if b != 16 || err != nil {
log.Fatal("failed to parse big float constant for sortition")
}
//hash value as int expression.
//hval, _ := h.Float64() to get the value
h := big.Float{}
h.SetPrec(precision)
h.SetInt(t)
ratio := big.Float{}
cratio, _ := ratio.Quo(&h, max).Float64()
return cratio
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment