Add Number func to random pkg

This commit is contained in:
Daniel 2019-05-06 10:36:46 +02:00
parent e97504dfba
commit 207844cb12
4 changed files with 61 additions and 7 deletions

View file

@ -6,7 +6,6 @@ import (
) )
func TestFeeder(t *testing.T) { func TestFeeder(t *testing.T) {
// wait for start / first round to complete // wait for start / first round to complete
time.Sleep(1 * time.Millisecond) time.Sleep(1 * time.Millisecond)

View file

@ -1,8 +1,10 @@
package random package random
import ( import (
"encoding/binary"
"errors" "errors"
"io" "io"
"math"
"time" "time"
"github.com/Safing/portbase/config" "github.com/Safing/portbase/config"
@ -94,3 +96,21 @@ func Bytes(n int) ([]byte, error) {
return rng.PseudoRandomData(uint(n)), nil return rng.PseudoRandomData(uint(n)), nil
} }
// Number returns a random number from 0 to (incl.) max.
func Number(max uint64) (uint64, error) {
secureLimit := math.MaxUint64 - (math.MaxUint64 % max)
max++
for {
randomBytes, err := Bytes(8)
if err != nil {
return 0, err
}
candidate := binary.LittleEndian.Uint64(randomBytes)
if candidate < secureLimit {
return candidate % max, nil
}
}
}

35
crypto/random/get_test.go Normal file
View file

@ -0,0 +1,35 @@
package random
import (
"testing"
)
func TestNumberRandomness(t *testing.T) {
if testing.Short() {
t.Skip()
}
var subjects uint64 = 10
var testSize uint64 = 10000
results := make([]uint64, int(subjects))
for i := 0; i < int(subjects*testSize); i++ {
n, err := Number(subjects - 1)
if err != nil {
t.Fatal(err)
return
}
results[int(n)]++
}
// catch big mistakes in the number function, eg. massive % bias
lowerMargin := testSize - testSize/50
upperMargin := testSize + testSize/50
for subject, result := range results {
if result < lowerMargin || result > upperMargin {
t.Errorf("subject %d is outside of margins: %d", subject, result)
}
}
t.Fatal(results)
}