This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
select_test.go
126 lines (103 loc) · 2.39 KB
/
select_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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package ipns
import (
"fmt"
"math/rand"
"testing"
"time"
pb "github.com/ipfs/go-ipns/pb"
"github.com/gogo/protobuf/proto"
u "github.com/ipfs/go-ipfs-util"
ci "github.com/libp2p/go-libp2p/core/crypto"
)
func shuffle(a []*pb.IpnsEntry) {
for n := 0; n < 5; n++ {
for i := range a {
j := rand.Intn(len(a))
a[i], a[j] = a[j], a[i]
}
}
}
func AssertSelected(r *pb.IpnsEntry, from ...*pb.IpnsEntry) error {
shuffle(from)
var vals [][]byte
for _, r := range from {
data, err := proto.Marshal(r)
if err != nil {
return err
}
vals = append(vals, data)
}
i, err := selectRecord(from, vals)
if err != nil {
return err
}
if from[i] != r {
return fmt.Errorf("selected incorrect record %d", i)
}
return nil
}
func TestOrdering(t *testing.T) {
// select timestamp so selection is deterministic
ts := time.Unix(1000000, 0)
// generate a key for signing the records
r := u.NewSeededRand(15) // generate deterministic keypair
priv, _, err := ci.GenerateKeyPairWithReader(ci.RSA, 2048, r)
if err != nil {
t.Fatal(err)
}
e1, err := Create(priv, []byte("foo"), 1, ts.Add(time.Hour), 0)
if err != nil {
t.Fatal(err)
}
e2, err := Create(priv, []byte("bar"), 2, ts.Add(time.Hour), 0)
if err != nil {
t.Fatal(err)
}
e3, err := Create(priv, []byte("baz"), 3, ts.Add(time.Hour), 0)
if err != nil {
t.Fatal(err)
}
e4, err := Create(priv, []byte("cat"), 3, ts.Add(time.Hour*2), 0)
if err != nil {
t.Fatal(err)
}
e5, err := Create(priv, []byte("dog"), 4, ts.Add(time.Hour*3), 0)
if err != nil {
t.Fatal(err)
}
e6, err := Create(priv, []byte("fish"), 4, ts.Add(time.Hour*3), 0)
if err != nil {
t.Fatal(err)
}
// e1 is the only record, i hope it gets this right
err = AssertSelected(e1, e1)
if err != nil {
t.Fatal(err)
}
// e2 has the highest sequence number
err = AssertSelected(e2, e1, e2)
if err != nil {
t.Fatal(err)
}
// e3 has the highest sequence number
err = AssertSelected(e3, e1, e2, e3)
if err != nil {
t.Fatal(err)
}
// e4 has a higher timeout
err = AssertSelected(e4, e1, e2, e3, e4)
if err != nil {
t.Fatal(err)
}
// e5 has the highest sequence number
err = AssertSelected(e5, e1, e2, e3, e4, e5)
if err != nil {
t.Fatal(err)
}
// e6 should be selected as its signauture will win in the comparison
err = AssertSelected(e6, e1, e2, e3, e4, e5, e6)
if err != nil {
t.Fatal(err)
}
_ = []interface{}{e1, e2, e3, e4, e5, e6}
}