forked from berty/go-libp2p-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
peer_gater_test.go
128 lines (105 loc) · 2.26 KB
/
peer_gater_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
127
128
package pubsub
import (
"context"
"testing"
"time"
"github.com/libp2p/go-libp2p/core/peer"
)
func TestPeerGater(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
peerA := peer.ID("A")
peerAip := "1.2.3.4"
params := NewPeerGaterParams(.1, .9, .999)
err := params.validate()
if err != nil {
t.Fatal(err)
}
pg := newPeerGater(ctx, nil, params)
pg.getIP = func(p peer.ID) string {
switch p {
case peerA:
return peerAip
default:
return "<wtf>"
}
}
pg.AddPeer(peerA, "")
status := pg.AcceptFrom(peerA)
if status != AcceptAll {
t.Fatal("expected AcceptAll")
}
msg := &Message{ReceivedFrom: peerA}
pg.ValidateMessage(msg)
status = pg.AcceptFrom(peerA)
if status != AcceptAll {
t.Fatal("expected AcceptAll")
}
pg.RejectMessage(msg, RejectValidationQueueFull)
status = pg.AcceptFrom(peerA)
if status != AcceptAll {
t.Fatal("expected AcceptAll")
}
pg.RejectMessage(msg, RejectValidationThrottled)
status = pg.AcceptFrom(peerA)
if status != AcceptAll {
t.Fatal("expected AcceptAll")
}
for i := 0; i < 100; i++ {
pg.RejectMessage(msg, RejectValidationIgnored)
pg.RejectMessage(msg, RejectValidationFailed)
}
accepted := false
for i := 0; !accepted && i < 1000; i++ {
status = pg.AcceptFrom(peerA)
if status == AcceptControl {
accepted = true
}
}
if !accepted {
t.Fatal("expected AcceptControl")
}
for i := 0; i < 100; i++ {
pg.DeliverMessage(msg)
}
accepted = false
for i := 0; !accepted && i < 1000; i++ {
status = pg.AcceptFrom(peerA)
if status == AcceptAll {
accepted = true
}
}
if !accepted {
t.Fatal("expected to accept at least once")
}
for i := 0; i < 100; i++ {
pg.decayStats()
}
status = pg.AcceptFrom(peerA)
if status != AcceptAll {
t.Fatal("expected AcceptAll")
}
pg.RemovePeer(peerA)
pg.Lock()
_, ok := pg.peerStats[peerA]
pg.Unlock()
if ok {
t.Fatal("still have a stat record for peerA")
}
pg.Lock()
_, ok = pg.ipStats[peerAip]
pg.Unlock()
if !ok {
t.Fatal("expected to still have a stat record for peerA's ip")
}
pg.Lock()
pg.ipStats[peerAip].expire = time.Now()
pg.Unlock()
time.Sleep(2 * time.Second)
pg.Lock()
_, ok = pg.ipStats["1.2.3.4"]
pg.Unlock()
if ok {
t.Fatal("still have a stat record for peerA's ip")
}
}