Last active
April 16, 2020 11:16
-
-
Save yoseplee/d08d51ec07058365dc4e561ec81854d3 to your computer and use it in GitHub Desktop.
a simple cryptographic sortition
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
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