prng_test.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright (c) 2018, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package prng
  20. import (
  21. "bytes"
  22. crypto_rand "crypto/rand"
  23. "fmt"
  24. "math"
  25. "math/big"
  26. "sort"
  27. "strings"
  28. "testing"
  29. "time"
  30. )
  31. func TestSeed(t *testing.T) {
  32. seed, err := NewSeed()
  33. if err != nil {
  34. t.Fatalf("NewSeed failed: %s", err)
  35. }
  36. prng1 := NewPRNGWithSeed(seed)
  37. prng2 := NewPRNGWithSeed(seed)
  38. for i := 1; i < 10000; i++ {
  39. bytes1 := make([]byte, i)
  40. prng1.Read(bytes1)
  41. bytes2 := make([]byte, i)
  42. prng2.Read(bytes2)
  43. zeroes := make([]byte, i)
  44. if bytes.Equal(zeroes, bytes1) {
  45. t.Fatalf("unexpected zero bytes")
  46. }
  47. if !bytes.Equal(bytes1, bytes2) {
  48. t.Fatalf("unexpected different bytes")
  49. }
  50. }
  51. prng1 = NewPRNGWithSeed(seed)
  52. prng3, err := NewPRNGWithSaltedSeed(seed, "3")
  53. if err != nil {
  54. t.Fatalf("NewPRNGWithSaltedSeed failed: %s", err)
  55. }
  56. prng4, err := NewPRNGWithSaltedSeed(seed, "4")
  57. if err != nil {
  58. t.Fatalf("NewPRNGWithSaltedSeed failed: %s", err)
  59. }
  60. for i := 1; i < 10000; i++ {
  61. bytes1 := make([]byte, i)
  62. prng1.Read(bytes1)
  63. bytes3 := make([]byte, i)
  64. prng3.Read(bytes3)
  65. bytes4 := make([]byte, i)
  66. prng4.Read(bytes4)
  67. if bytes.Equal(bytes1, bytes3) {
  68. t.Fatalf("unexpected identical bytes")
  69. }
  70. if bytes.Equal(bytes3, bytes4) {
  71. t.Fatalf("unexpected identical bytes")
  72. }
  73. }
  74. }
  75. func TestFlipWeightedCoin(t *testing.T) {
  76. runs := 100000
  77. tolerance := 1000
  78. testCases := []struct {
  79. weight float64
  80. expectedTrues int
  81. }{
  82. {0.333, runs / 3},
  83. {0.5, runs / 2},
  84. {1.0, runs},
  85. {0.0, 0},
  86. }
  87. for _, testCase := range testCases {
  88. t.Run(fmt.Sprintf("%f", testCase.weight), func(t *testing.T) {
  89. p, err := NewPRNG()
  90. if err != nil {
  91. t.Fatalf("NewPRNG failed: %s", err)
  92. }
  93. trues := 0
  94. for i := 0; i < runs; i++ {
  95. if p.FlipWeightedCoin(testCase.weight) {
  96. trues++
  97. }
  98. }
  99. min := testCase.expectedTrues - tolerance
  100. if min < 0 {
  101. min = 0
  102. }
  103. max := testCase.expectedTrues + tolerance
  104. if trues < min || trues > max {
  105. t.Errorf("unexpected coin flip outcome: %f %d (+/-%d) %d",
  106. testCase.weight, testCase.expectedTrues, tolerance, trues)
  107. }
  108. })
  109. }
  110. }
  111. func TestPerm(t *testing.T) {
  112. p, err := NewPRNG()
  113. if err != nil {
  114. t.Fatalf("NewPRNG failed: %s", err)
  115. }
  116. for n := 0; n < 1000; n++ {
  117. perm := p.Perm(n)
  118. if len(perm) != n {
  119. t.Error("unexpected permutation size")
  120. }
  121. sum := 0
  122. for i := 0; i < n; i++ {
  123. sum += perm[i]
  124. }
  125. expectedSum := (n * (n - 1)) / 2
  126. if sum != expectedSum {
  127. t.Error("unexpected permutation")
  128. }
  129. }
  130. }
  131. func TestRange(t *testing.T) {
  132. p, err := NewPRNG()
  133. if err != nil {
  134. t.Fatalf("NewPRNG failed: %s", err)
  135. }
  136. min := 1
  137. max := 19
  138. var gotMin, gotMax bool
  139. for n := 0; n < 1000; n++ {
  140. i := p.Range(min, max)
  141. if i < min || i > max {
  142. t.Error("out of range")
  143. }
  144. if i == min {
  145. gotMin = true
  146. }
  147. if i == max {
  148. gotMax = true
  149. }
  150. }
  151. if !gotMin {
  152. t.Error("missing min")
  153. }
  154. if !gotMax {
  155. t.Error("missing max")
  156. }
  157. }
  158. func TestUint32Range(t *testing.T) {
  159. p, err := NewPRNG()
  160. if err != nil {
  161. t.Fatalf("NewPRNG failed: %s", err)
  162. }
  163. var min uint32 = math.MaxUint32 - 19
  164. var max uint32 = math.MaxUint32
  165. var gotMin, gotMax bool
  166. for n := 0; n < 1000; n++ {
  167. i := p.RangeUint32(min, max)
  168. if i < min || i > max {
  169. t.Error("out of range")
  170. }
  171. if i == min {
  172. gotMin = true
  173. }
  174. if i == max {
  175. gotMax = true
  176. }
  177. }
  178. if !gotMin {
  179. t.Error("missing min")
  180. }
  181. if !gotMax {
  182. t.Error("missing max")
  183. }
  184. }
  185. func TestPeriod(t *testing.T) {
  186. p, err := NewPRNG()
  187. if err != nil {
  188. t.Fatalf("NewPRNG failed: %s", err)
  189. }
  190. min := 1 * time.Nanosecond
  191. max := 10000 * time.Nanosecond
  192. different := 0
  193. for n := 0; n < 1000; n++ {
  194. res1 := p.Period(min, max)
  195. if res1 < min {
  196. t.Error("duration should not be less than min")
  197. }
  198. if res1 > max {
  199. t.Error("duration should not be more than max")
  200. }
  201. res2 := p.Period(min, max)
  202. if res1 != res2 {
  203. different += 1
  204. }
  205. }
  206. // res1 and res2 should be different most of the time, but it's possible
  207. // to get the same result twice in a row.
  208. if different < 900 {
  209. t.Error("duration insufficiently random")
  210. }
  211. }
  212. func TestJitter(t *testing.T) {
  213. testCases := []struct {
  214. n int64
  215. factor float64
  216. expectedMin int64
  217. expectedMax int64
  218. }{
  219. {100, 0.1, 90, 110},
  220. {1000, 0.3, 700, 1300},
  221. }
  222. for _, testCase := range testCases {
  223. t.Run(fmt.Sprintf("Jitter case: %+v", testCase), func(t *testing.T) {
  224. p, err := NewPRNG()
  225. if err != nil {
  226. t.Fatalf("NewPRNG failed: %s", err)
  227. }
  228. min := int64(math.MaxInt64)
  229. max := int64(0)
  230. for i := 0; i < 100000; i++ {
  231. x := p.Jitter(testCase.n, testCase.factor)
  232. if x < min {
  233. min = x
  234. }
  235. if x > max {
  236. max = x
  237. }
  238. }
  239. if min != testCase.expectedMin {
  240. t.Errorf("unexpected minimum jittered value: %d", min)
  241. }
  242. if max != testCase.expectedMax {
  243. t.Errorf("unexpected maximum jittered value: %d", max)
  244. }
  245. })
  246. }
  247. }
  248. func TestIntn(t *testing.T) {
  249. p, err := NewPRNG()
  250. if err != nil {
  251. t.Fatalf("NewPRNG failed: %s", err)
  252. }
  253. for max := 0; max <= 255; max++ {
  254. counts := make(map[int]int)
  255. repeats := 200000
  256. for r := 0; r < repeats; r++ {
  257. value := p.Intn(max)
  258. if value < 0 || value > max {
  259. t.Fatalf("unexpected value: max = %d, value = %d", max, value)
  260. }
  261. counts[value] += 1
  262. }
  263. expected := repeats / (max + 1)
  264. for i := 0; i < max; i++ {
  265. if counts[i] < (expected/10)*8 {
  266. t.Logf("max = %d, counts = %+v", max, counts)
  267. t.Fatalf("unexpected low count: max = %d, i = %d, count = %d", max, i, counts[i])
  268. }
  269. }
  270. }
  271. }
  272. func TestExpFloat64Range(t *testing.T) {
  273. testCases := []struct {
  274. min, max, lambda float64
  275. factor int
  276. }{
  277. {1.0, 3.0, 2.0, 5},
  278. {0.0, 1.0, 2.0, 5},
  279. {-2.0, -1.0, 2.0, 5},
  280. }
  281. for _, testCase := range testCases {
  282. t.Run(fmt.Sprintf("ExpFloat64Range case: %+v", testCase), func(t *testing.T) {
  283. p, err := NewPRNG()
  284. if err != nil {
  285. t.Fatalf("NewPRNG failed: %s", err)
  286. }
  287. buckets := make(map[float64]int)
  288. for i := 0; i < 100000; i++ {
  289. value := p.ExpFloat64Range(testCase.min, testCase.max, testCase.lambda)
  290. if value < testCase.min || value > testCase.max {
  291. t.Fatalf(
  292. "unexpected value: %f [%f, %f]", value, testCase.min, testCase.max)
  293. }
  294. buckets[float64(int(10.0*(value)))/10.0] += 1
  295. }
  296. keys := make([]float64, 0)
  297. for k := range buckets {
  298. keys = append(keys, k)
  299. }
  300. sort.Float64s(keys)
  301. strs := make([]string, 0)
  302. for _, k := range keys {
  303. strs = append(strs, fmt.Sprintf("%0.2f: %d", k, buckets[k]))
  304. }
  305. t.Logf(strings.Join(strs, ","))
  306. for i := 0; i < len(keys)-1; i++ {
  307. if buckets[keys[i]] <= buckets[keys[i+1]] {
  308. t.Fatalf("unexpected distribution")
  309. }
  310. }
  311. // First bucket should have at least "factor" times more items than last
  312. // bucket.
  313. if buckets[keys[0]]/buckets[keys[len(keys)-1]] < testCase.factor {
  314. t.Fatalf("unexpected distribution")
  315. }
  316. })
  317. }
  318. }
  319. //lint:ignore U1000 intentionally unused
  320. func Disabled_TestRandomStreamLimit(t *testing.T) {
  321. // This test takes up to ~2 minute to complete, so it's disabled by default.
  322. p, err := NewPRNG()
  323. if err != nil {
  324. t.Fatalf("NewPRNG failed: %s", err)
  325. }
  326. // Use large blocks to get close to the key stream limit.
  327. var b [2 * 1024 * 1024 * 1024]byte
  328. n := int64(0)
  329. for i := 0; i < 127; i++ {
  330. p.Read(b[:])
  331. n += int64(len(b))
  332. }
  333. // Stop using large blocks 64 bytes short of the limit, 2^38-64.
  334. p.Read(b[0 : len(b)-128])
  335. n += int64(len(b) - 128)
  336. // Invoke byte at a time across the limit boundary to ensure we
  337. // don't jump over the limit case.
  338. for i := 0; i < 192; i++ {
  339. p.Read(b[0:1])
  340. n += int64(1)
  341. }
  342. }
  343. func BenchmarkIntn(b *testing.B) {
  344. p, err := NewPRNG()
  345. if err != nil {
  346. b.Fatalf("NewPRNG failed: %s", err)
  347. }
  348. max := 255
  349. b.Run("PRNG", func(b *testing.B) {
  350. for n := 0; n < b.N; n++ {
  351. _ = p.Intn(n % max)
  352. }
  353. })
  354. b.Run("getrandom()", func(b *testing.B) {
  355. for n := 0; n < b.N; n++ {
  356. _, err := crypto_rand.Int(crypto_rand.Reader, big.NewInt(int64(max)))
  357. if err != nil {
  358. b.Fatalf("crypto_rand.Int failed: %s", err)
  359. }
  360. }
  361. })
  362. }