-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
peermanager_scoring_test.go
80 lines (72 loc) · 2.16 KB
/
peermanager_scoring_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
package p2p
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/crypto/ed25519"
dbm "github.com/tendermint/tm-db"
)
func TestPeerScoring(t *testing.T) {
// coppied from p2p_test shared variables
selfKey := ed25519.GenPrivKeyFromSecret([]byte{0xf9, 0x1b, 0x08, 0xaa, 0x38, 0xee, 0x34, 0xdd})
selfID := NodeIDFromPubKey(selfKey.PubKey())
// create a mock peer manager
db := dbm.NewMemDB()
peerManager, err := NewPeerManager(selfID, db, PeerManagerOptions{})
require.NoError(t, err)
defer peerManager.Close()
// create a fake node
id := NodeID(strings.Repeat("a1", 20))
added, err := peerManager.Add(NodeAddress{NodeID: id, Protocol: "memory"})
require.NoError(t, err)
require.True(t, added)
t.Run("Synchronous", func(t *testing.T) {
// update the manager and make sure it's correct
require.EqualValues(t, 0, peerManager.Scores()[id])
// add a bunch of good status updates and watch things increase.
for i := 1; i < 10; i++ {
peerManager.processPeerEvent(PeerUpdate{
NodeID: id,
Status: PeerStatusGood,
})
require.EqualValues(t, i, peerManager.Scores()[id])
}
// watch the corresponding decreases respond to update
for i := 10; i == 0; i-- {
peerManager.processPeerEvent(PeerUpdate{
NodeID: id,
Status: PeerStatusBad,
})
require.EqualValues(t, i, peerManager.Scores()[id])
}
})
t.Run("AsynchronousIncrement", func(t *testing.T) {
start := peerManager.Scores()[id]
pu := peerManager.Subscribe()
defer pu.Close()
pu.SendUpdate(PeerUpdate{
NodeID: id,
Status: PeerStatusGood,
})
require.Eventually(t,
func() bool { return start+1 == peerManager.Scores()[id] },
time.Second,
time.Millisecond,
"startAt=%d score=%d", start, peerManager.Scores()[id])
})
t.Run("AsynchronousDecrement", func(t *testing.T) {
start := peerManager.Scores()[id]
pu := peerManager.Subscribe()
defer pu.Close()
pu.SendUpdate(PeerUpdate{
NodeID: id,
Status: PeerStatusBad,
})
require.Eventually(t,
func() bool { return start-1 == peerManager.Scores()[id] },
time.Second,
time.Millisecond,
"startAt=%d score=%d", start, peerManager.Scores()[id])
})
}