...
1 package common
2
3 import (
4 "crypto/rand"
5 "encoding/binary"
6 "math"
7 "testing"
8 )
9
10 func randSliceUint32(length uint) []uint32 { return randSliceUint32WithMax(length, math.MaxUint32) }
11
12 func randSliceUint32WithMax(length uint, max uint32) []uint32 {
13 bytes := make([]uint8, 4*length)
14 if n, err := rand.Read(bytes); err != nil {
15 panic(err)
16 } else if n < len(bytes) {
17 panic("short read from RNG")
18 }
19 x := make([]uint32, length)
20 for i := range x {
21 x[i] = binary.LittleEndian.Uint32(bytes[4*i:]) % max
22 }
23 return x
24 }
25
26 func TestModQ(t *testing.T) {
27 const testTimes = 1000
28 r := randSliceUint32(testTimes)
29 for i := 0; i < testTimes; i++ {
30 x := r[i]
31 y := modQ(x)
32 if y > Q {
33 t.Fatalf("modQ(%d) > Q", x)
34 }
35 if y != x%Q {
36 t.Fatalf("modQ(%d) != %d (mod Q)", x, x)
37 }
38 }
39 }
40
41 func TestReduceLe2Q(t *testing.T) {
42 const testTimes = 1000
43 r := randSliceUint32(testTimes)
44 for i := 0; i < testTimes; i++ {
45 x := r[i]
46 y := ReduceLe2Q(x)
47 if y > 2*Q {
48 t.Fatalf("reduce_le2q(%d) > 2Q", x)
49 }
50 if y%Q != x%Q {
51 t.Fatalf("reduce_le2q(%d) != %d (mod Q)", x, x)
52 }
53 }
54 }
55
56 func TestPower2Round(t *testing.T) {
57 for a := uint32(0); a < Q; a++ {
58 a0PlusQ, a1 := power2round(a)
59 a0 := int32(a0PlusQ) - int32(Q)
60 if int32(a) != a0+int32((1<<D)*a1) {
61 t.Fatalf("power2round(%v) doesn't recombine", a)
62 }
63 if (-(1 << (D - 1)) >= a0) || (a0 > 1<<(D-1)) {
64 t.Fatalf("power2round(%v): a0 out of bounds", a)
65 }
66 if a1 > (1 << (QBits - D)) {
67 t.Fatalf("power2round(%v): a1 out of bounds", a)
68 }
69 }
70 }
71
View as plain text