|
| 1 | +// Entropy generates fully deterministic, cost-effective, and hard to guess |
| 2 | +// numbers. |
| 3 | +// |
| 4 | +// It is designed both for single-usage, like seeding math/rand or for being |
| 5 | +// reused which increases the entropy and its cost effectiveness. |
| 6 | +// |
| 7 | +// Disclaimer: this package is unsafe and won't prevent others to guess values |
| 8 | +// in advance. |
| 9 | +// |
| 10 | +// It uses the Bernstein's hash djb2 to be CPU-cycle efficient. |
| 11 | +package entropy |
| 12 | + |
| 13 | +import ( |
| 14 | + "math" |
| 15 | + "std" |
| 16 | + "time" |
| 17 | +) |
| 18 | + |
| 19 | +type Instance struct { |
| 20 | + value uint32 |
| 21 | +} |
| 22 | + |
| 23 | +func New() *Instance { |
| 24 | + r := Instance{value: 5381} |
| 25 | + r.addEntropy() |
| 26 | + return &r |
| 27 | +} |
| 28 | + |
| 29 | +func FromSeed(seed uint32) *Instance { |
| 30 | + r := Instance{value: seed} |
| 31 | + r.addEntropy() |
| 32 | + return &r |
| 33 | +} |
| 34 | + |
| 35 | +func (i *Instance) Seed() uint32 { |
| 36 | + return i.value |
| 37 | +} |
| 38 | + |
| 39 | +func (i *Instance) djb2String(input string) { |
| 40 | + for _, c := range input { |
| 41 | + i.djb2Uint32(uint32(c)) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// super fast random algorithm. |
| 46 | +// http://www.cse.yorku.ca/~oz/hash.html |
| 47 | +func (i *Instance) djb2Uint32(input uint32) { |
| 48 | + i.value = (i.value << 5) + i.value + input |
| 49 | +} |
| 50 | + |
| 51 | +// AddEntropy uses various runtime variables to add entropy to the existing seed. |
| 52 | +func (i *Instance) addEntropy() { |
| 53 | + // FIXME: reapply the 5381 initial value? |
| 54 | + |
| 55 | + // inherit previous entropy |
| 56 | + // nothing to do |
| 57 | + |
| 58 | + // handle callers |
| 59 | + { |
| 60 | + caller1 := std.GetCallerAt(1).String() |
| 61 | + i.djb2String(caller1) |
| 62 | + caller2 := std.GetCallerAt(2).String() |
| 63 | + i.djb2String(caller2) |
| 64 | + } |
| 65 | + |
| 66 | + // height |
| 67 | + { |
| 68 | + height := std.GetHeight() |
| 69 | + if height >= math.MaxUint32 { |
| 70 | + height -= math.MaxUint32 |
| 71 | + } |
| 72 | + i.djb2Uint32(uint32(height)) |
| 73 | + } |
| 74 | + |
| 75 | + // time |
| 76 | + { |
| 77 | + secs := time.Now().Second() |
| 78 | + i.djb2Uint32(uint32(secs)) |
| 79 | + nsecs := time.Now().Nanosecond() |
| 80 | + i.djb2Uint32(uint32(nsecs)) |
| 81 | + } |
| 82 | + |
| 83 | + // FIXME: compute other hard-to-guess but deterministic variables, like real gas? |
| 84 | +} |
| 85 | + |
| 86 | +func (i *Instance) Value() uint32 { |
| 87 | + i.addEntropy() |
| 88 | + return i.value |
| 89 | +} |
0 commit comments