-
Notifications
You must be signed in to change notification settings - Fork 11
/
test.go
103 lines (82 loc) · 1.78 KB
/
test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// SPDX-FileCopyrightText: 2023 Steffen Vogel <post@steffenvogel.de>
// SPDX-License-Identifier: Apache-2.0
// Package test implements universal helpers for unit and integration tests
package test
import (
"bytes"
"crypto/rand"
"math"
"math/big"
"os"
"sync"
"golang.org/x/sync/errgroup"
"cunicu.li/cunicu/pkg/crypto"
epdiscproto "cunicu.li/cunicu/pkg/proto/feature/epdisc"
"cunicu.li/cunicu/pkg/signaling"
)
func GenerateKeyPairs() (*crypto.KeyPair, *crypto.KeyPair, error) {
ourKey, err := crypto.GeneratePrivateKey()
if err != nil {
return nil, nil, err
}
theirKey, err := crypto.GeneratePrivateKey()
if err != nil {
return nil, nil, err
}
return &crypto.KeyPair{
Ours: ourKey,
Theirs: theirKey.PublicKey(),
}, &crypto.KeyPair{
Ours: theirKey,
Theirs: ourKey.PublicKey(),
}, nil
}
func GenerateSignalingMessage() *signaling.Message {
r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
if err != nil {
panic(err)
}
return &signaling.Message{
Candidate: &epdiscproto.Candidate{
Port: int32(r.Int64()),
},
}
}
func Entropy(data []byte) float64 {
if len(data) == 0 {
return 0
}
length := float64(len(data))
entropy := 0.0
for i := 0; i < 256; i++ {
if p := float64(bytes.Count(data, []byte{byte(i)})) / length; p > 0 {
entropy += -p * math.Log2(p)
}
}
return entropy
}
func IsCI() bool {
return os.Getenv("CI") == "true"
}
func ParallelNew[T any](cnt int, ctor func(i int) (T, error)) ([]T, error) {
ts := []T{}
mu := sync.Mutex{}
eg := errgroup.Group{}
for i := 1; i <= cnt; i++ {
i := i
eg.Go(func() error {
t, err := ctor(i)
if err != nil {
return err
}
mu.Lock()
ts = append(ts, t)
mu.Unlock()
return nil
})
}
if err := eg.Wait(); err != nil {
return nil, err
}
return ts, nil
}