-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrandom_tree.go
53 lines (48 loc) · 1.23 KB
/
random_tree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package ssp
import (
"crypto/rand"
"fmt"
"log"
"time"
)
// RandomTree produces random nuts
type RandomTree struct {
byteSize int
valueChan chan Nut
}
// NewRandomTree takes a bytesize between 8 and 20
// Shorter nuts are preferred; but if you think your
// deployment would require more bits to be unique you
// can create larger ones
func NewRandomTree(byteSize int) (*RandomTree, error) {
if byteSize < 8 || byteSize > 20 {
return nil, fmt.Errorf("Valid sizes are between 8 and 20 bytes")
}
rt := &RandomTree{
byteSize: byteSize,
valueChan: make(chan Nut, 1000), // buffer a thousand values to smooth out load on the enrtopy source
}
go rt.valueReader()
return rt, nil
}
func (rt *RandomTree) valueReader() {
for {
valueBytes := make([]byte, rt.byteSize)
_, err := rand.Read(valueBytes)
if err != nil {
log.Printf("error reading random bytes: %v", err)
time.Sleep(time.Millisecond * 10)
continue
}
rt.valueChan <- Nut(Sqrl64.EncodeToString(valueBytes))
}
}
// Nut Create a pure random nut
func (rt *RandomTree) Nut() (Nut, error) {
select {
case val := <-rt.valueChan:
return val, nil
case <-time.After(20 * time.Millisecond):
return "", fmt.Errorf("timeout failed waiting for random nut generation")
}
}