prng_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 TestPeriod(t *testing.T) {
  159. p, err := NewPRNG()
  160. if err != nil {
  161. t.Fatalf("NewPRNG failed: %s", err)
  162. }
  163. min := 1 * time.Nanosecond
  164. max := 10000 * time.Nanosecond
  165. different := 0
  166. for n := 0; n < 1000; n++ {
  167. res1 := p.Period(min, max)
  168. if res1 < min {
  169. t.Error("duration should not be less than min")
  170. }
  171. if res1 > max {
  172. t.Error("duration should not be more than max")
  173. }
  174. res2 := p.Period(min, max)
  175. if res1 != res2 {
  176. different += 1
  177. }
  178. }
  179. // res1 and res2 should be different most of the time, but it's possible
  180. // to get the same result twice in a row.
  181. if different < 900 {
  182. t.Error("duration insufficiently random")
  183. }
  184. }
  185. func TestJitter(t *testing.T) {
  186. testCases := []struct {
  187. n int64
  188. factor float64
  189. expectedMin int64
  190. expectedMax int64
  191. }{
  192. {100, 0.1, 90, 110},
  193. {1000, 0.3, 700, 1300},
  194. }
  195. for _, testCase := range testCases {
  196. t.Run(fmt.Sprintf("Jitter case: %+v", testCase), func(t *testing.T) {
  197. p, err := NewPRNG()
  198. if err != nil {
  199. t.Fatalf("NewPRNG failed: %s", err)
  200. }
  201. min := int64(math.MaxInt64)
  202. max := int64(0)
  203. for i := 0; i < 100000; i++ {
  204. x := p.Jitter(testCase.n, testCase.factor)
  205. if x < min {
  206. min = x
  207. }
  208. if x > max {
  209. max = x
  210. }
  211. }
  212. if min != testCase.expectedMin {
  213. t.Errorf("unexpected minimum jittered value: %d", min)
  214. }
  215. if max != testCase.expectedMax {
  216. t.Errorf("unexpected maximum jittered value: %d", max)
  217. }
  218. })
  219. }
  220. }
  221. func TestIntn(t *testing.T) {
  222. p, err := NewPRNG()
  223. if err != nil {
  224. t.Fatalf("NewPRNG failed: %s", err)
  225. }
  226. for max := 0; max <= 255; max++ {
  227. counts := make(map[int]int)
  228. repeats := 200000
  229. for r := 0; r < repeats; r++ {
  230. value := p.Intn(max)
  231. if value < 0 || value > max {
  232. t.Fatalf("unexpected value: max = %d, value = %d", max, value)
  233. }
  234. counts[value] += 1
  235. }
  236. expected := repeats / (max + 1)
  237. for i := 0; i < max; i++ {
  238. if counts[i] < (expected/10)*8 {
  239. t.Logf("max = %d, counts = %+v", max, counts)
  240. t.Fatalf("unexpected low count: max = %d, i = %d, count = %d", max, i, counts[i])
  241. }
  242. }
  243. }
  244. }
  245. func TestExpFloat64Range(t *testing.T) {
  246. testCases := []struct {
  247. min, max, lambda float64
  248. factor int
  249. }{
  250. {1.0, 3.0, 2.0, 5},
  251. {0.0, 1.0, 2.0, 5},
  252. {-2.0, -1.0, 2.0, 5},
  253. }
  254. for _, testCase := range testCases {
  255. t.Run(fmt.Sprintf("ExpFloat64Range case: %+v", testCase), func(t *testing.T) {
  256. p, err := NewPRNG()
  257. if err != nil {
  258. t.Fatalf("NewPRNG failed: %s", err)
  259. }
  260. buckets := make(map[float64]int)
  261. for i := 0; i < 100000; i++ {
  262. value := p.ExpFloat64Range(testCase.min, testCase.max, testCase.lambda)
  263. if value < testCase.min || value > testCase.max {
  264. t.Fatalf(
  265. "unexpected value: %f [%f, %f]", value, testCase.min, testCase.max)
  266. }
  267. buckets[float64(int(10.0*(value)))/10.0] += 1
  268. }
  269. keys := make([]float64, 0)
  270. for k := range buckets {
  271. keys = append(keys, k)
  272. }
  273. sort.Float64s(keys)
  274. strs := make([]string, 0)
  275. for _, k := range keys {
  276. strs = append(strs, fmt.Sprintf("%0.2f: %d", k, buckets[k]))
  277. }
  278. t.Logf(strings.Join(strs, ","))
  279. for i := 0; i < len(keys)-1; i++ {
  280. if buckets[keys[i]] <= buckets[keys[i+1]] {
  281. t.Fatalf("unexpected distribution")
  282. }
  283. }
  284. // First bucket should have at least "factor" times more items than last
  285. // bucket.
  286. if buckets[keys[0]]/buckets[keys[len(keys)-1]] < testCase.factor {
  287. t.Fatalf("unexpected distribution")
  288. }
  289. })
  290. }
  291. }
  292. //lint:ignore U1000 intentionally unused
  293. func Disabled_TestRandomStreamLimit(t *testing.T) {
  294. // This test takes up to ~2 minute to complete, so it's disabled by default.
  295. p, err := NewPRNG()
  296. if err != nil {
  297. t.Fatalf("NewPRNG failed: %s", err)
  298. }
  299. // Use large blocks to get close to the key stream limit.
  300. var b [2 * 1024 * 1024 * 1024]byte
  301. n := int64(0)
  302. for i := 0; i < 127; i++ {
  303. p.Read(b[:])
  304. n += int64(len(b))
  305. }
  306. // Stop using large blocks 64 bytes short of the limit, 2^38-64.
  307. p.Read(b[0 : len(b)-128])
  308. n += int64(len(b) - 128)
  309. // Invoke byte at a time across the limit boundary to ensure we
  310. // don't jump over the limit case.
  311. for i := 0; i < 192; i++ {
  312. p.Read(b[0:1])
  313. n += int64(1)
  314. }
  315. }
  316. func BenchmarkIntn(b *testing.B) {
  317. p, err := NewPRNG()
  318. if err != nil {
  319. b.Fatalf("NewPRNG failed: %s", err)
  320. }
  321. max := 255
  322. b.Run("PRNG", func(b *testing.B) {
  323. for n := 0; n < b.N; n++ {
  324. _ = p.Intn(n % max)
  325. }
  326. })
  327. b.Run("getrandom()", func(b *testing.B) {
  328. for n := 0; n < b.N; n++ {
  329. _, err := crypto_rand.Int(crypto_rand.Reader, big.NewInt(int64(max)))
  330. if err != nil {
  331. b.Fatalf("crypto_rand.Int failed: %s", err)
  332. }
  333. }
  334. })
  335. }