cprng.go raw

   1  package txauthor
   2  
   3  import (
   4  	"crypto/rand"
   5  	"encoding/binary"
   6  	mrand "math/rand"
   7  	"sync"
   8  )
   9  
  10  // cprng is a cryptographically random-seeded math/rand prng. It is seeded
  11  // during package init. Any initialization errors result in panics. It is safe
  12  // for concurrent access.
  13  var cprng = cprngType{}
  14  
  15  type cprngType struct {
  16  	r  *mrand.Rand
  17  	mu sync.Mutex
  18  }
  19  
  20  func init() {
  21  	buf := make([]byte, 8)
  22  	_, e := rand.Read(buf)
  23  	if e != nil {
  24  		panic("Failed to seed prng: " + e.Error())
  25  	}
  26  	seed := int64(binary.LittleEndian.Uint64(buf))
  27  	cprng.r = mrand.New(mrand.NewSource(seed))
  28  }
  29  func (c *cprngType) Int31n(n int32) int32 {
  30  	defer c.mu.Unlock() // Int31n may panic
  31  	c.mu.Lock()
  32  	return c.r.Int31n(n)
  33  }
  34