decred.org/dcrwallet/v3@v3.1.0/wallet/txauthor/cprng.go (about) 1 // Copyright (c) 2016 The btcsuite developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package txauthor 6 7 import ( 8 "crypto/rand" 9 "sync" 10 11 "decred.org/dcrwallet/v3/internal/uniformprng" 12 ) 13 14 // cprng is a cryptographically random-seeded prng. It is seeded during package 15 // init. Any initialization errors result in panics. It is safe for concurrent 16 // access. 17 var cprng = cprngType{} 18 19 type cprngType struct { 20 r *uniformprng.Source 21 mu sync.Mutex 22 } 23 24 func init() { 25 r, err := uniformprng.RandSource(rand.Reader) 26 if err != nil { 27 panic("Failed to seed prng: " + err.Error()) 28 } 29 cprng.r = r 30 } 31 32 func (c *cprngType) Int31n(n int32) int32 { 33 defer c.mu.Unlock() 34 c.mu.Lock() 35 36 if n <= 0 { 37 panic("Int31n: non-positive n") 38 } 39 return int32(c.r.Uint32n(uint32(n))) 40 }