forked from cometbft/cometbft
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreactor_test.go
More file actions
358 lines (307 loc) · 9.49 KB
/
Copy pathreactor_test.go
File metadata and controls
358 lines (307 loc) · 9.49 KB
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package mempool
import (
"encoding/hex"
"errors"
"sync"
"testing"
"time"
"github.com/fortytw2/leaktest"
"github.com/go-kit/log/term"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/cometbft/cometbft/abci/example/kvstore"
abci "github.com/cometbft/cometbft/abci/types"
cfg "github.com/cometbft/cometbft/config"
"github.com/cometbft/cometbft/libs/log"
"github.com/cometbft/cometbft/p2p"
memproto "github.com/cometbft/cometbft/proto/tendermint/mempool"
"github.com/cometbft/cometbft/proxy"
"github.com/cometbft/cometbft/types"
)
const (
numTxs = 1000
timeout = 120 * time.Second // ridiculously high because CircleCI is slow
)
type peerState struct {
height int64
}
func (ps peerState) GetHeight() int64 {
return ps.height
}
// Send a bunch of txs to the first reactor's mempool and wait for them all to
// be received in the others.
func TestReactorBroadcastTxsMessage(t *testing.T) {
config := cfg.TestConfig()
// if there were more than two reactors, the order of transactions could not be
// asserted in waitForTxsOnReactors (due to transactions gossiping). If we
// replace Connect2Switches (full mesh) with a func, which connects first
// reactor to others and nothing else, this test should also pass with >2 reactors.
const N = 2
reactors, _ := makeAndConnectReactors(config, N)
defer func() {
for _, r := range reactors {
if err := r.Stop(); err != nil {
assert.NoError(t, err)
}
}
}()
for _, r := range reactors {
for _, peer := range r.Switch.Peers().Copy() {
peer.Set(types.PeerStateKey, peerState{1})
}
}
txs := addRandomTxs(t, reactors[0].mempool, numTxs, UnknownPeerID)
waitForTxsOnReactors(t, txs, reactors)
}
// regression test for https://github.com/cometbft/cometbft/issues/5408
func TestReactorConcurrency(t *testing.T) {
config := cfg.TestConfig()
const N = 2
reactors, _ := makeAndConnectReactors(config, N)
defer func() {
for _, r := range reactors {
if err := r.Stop(); err != nil {
assert.NoError(t, err)
}
}
}()
for _, r := range reactors {
for _, peer := range r.Switch.Peers().Copy() {
peer.Set(types.PeerStateKey, peerState{1})
}
}
var wg sync.WaitGroup
const numTxs = 5
for i := 0; i < 1000; i++ {
wg.Add(2)
// 1. submit a bunch of txs
// 2. update the whole mempool
txs := addRandomTxs(t, reactors[0].mempool, numTxs, UnknownPeerID)
go func() {
defer wg.Done()
reactors[0].mempool.Lock()
defer reactors[0].mempool.Unlock()
txResponses := make([]*abci.ExecTxResult, len(txs))
for i := range txs {
txResponses[i] = &abci.ExecTxResult{Code: 0}
}
err := reactors[0].mempool.Update(1, txs, txResponses, nil, nil)
assert.NoError(t, err)
}()
// 1. submit a bunch of txs
// 2. update none
_ = addRandomTxs(t, reactors[1].mempool, numTxs, UnknownPeerID)
go func() {
defer wg.Done()
reactors[1].mempool.Lock()
defer reactors[1].mempool.Unlock()
err := reactors[1].mempool.Update(1, []types.Tx{}, make([]*abci.ExecTxResult, 0), nil, nil)
assert.NoError(t, err)
}()
// 1. flush the mempool
reactors[1].mempool.Flush()
}
wg.Wait()
}
// Send a bunch of txs to the first reactor's mempool, claiming it came from peer
// ensure peer gets no txs.
func TestReactorNoBroadcastToSender(t *testing.T) {
config := cfg.TestConfig()
const N = 2
reactors, _ := makeAndConnectReactors(config, N)
defer func() {
for _, r := range reactors {
if err := r.Stop(); err != nil {
assert.NoError(t, err)
}
}
}()
for _, r := range reactors {
for _, peer := range r.Switch.Peers().Copy() {
peer.Set(types.PeerStateKey, peerState{1})
}
}
const peerID = 1
addRandomTxs(t, reactors[0].mempool, numTxs, peerID)
ensureNoTxs(t, reactors[peerID], 100*time.Millisecond)
}
func TestMempoolReactorMaxTxBytes(t *testing.T) {
config := cfg.TestConfig()
const N = 2
reactors, _ := makeAndConnectReactors(config, N)
defer func() {
for _, r := range reactors {
if err := r.Stop(); err != nil {
assert.NoError(t, err)
}
}
}()
for _, r := range reactors {
for _, peer := range r.Switch.Peers().Copy() {
peer.Set(types.PeerStateKey, peerState{1})
}
}
// Broadcast a tx, which has the max size
// => ensure it's received by the second reactor.
tx1 := kvstore.NewRandomTx(config.Mempool.MaxTxBytes)
err := reactors[0].mempool.CheckTx(tx1, func(resp *abci.ResponseCheckTx) {
require.False(t, resp.IsErr())
}, TxInfo{SenderID: UnknownPeerID})
require.NoError(t, err)
waitForTxsOnReactors(t, []types.Tx{tx1}, reactors)
reactors[0].mempool.Flush()
reactors[1].mempool.Flush()
// Broadcast a tx, which is beyond the max size
// => ensure it's not sent
tx2 := kvstore.NewRandomTx(config.Mempool.MaxTxBytes + 1)
err = reactors[0].mempool.CheckTx(tx2, func(resp *abci.ResponseCheckTx) {
require.False(t, resp.IsErr())
}, TxInfo{SenderID: UnknownPeerID})
require.Error(t, err)
}
func TestBroadcastTxForPeerStopsWhenPeerStops(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
config := cfg.TestConfig()
const N = 2
reactors, _ := makeAndConnectReactors(config, N)
defer func() {
for _, r := range reactors {
if err := r.Stop(); err != nil {
assert.NoError(t, err)
}
}
}()
// stop peer
sw := reactors[1].Switch
sw.StopPeerForError(sw.Peers().Copy()[0], errors.New("some reason"))
// check that we are not leaking any go-routines
// i.e. broadcastTxRoutine finishes when peer is stopped
leaktest.CheckTimeout(t, 10*time.Second)()
}
func TestBroadcastTxForPeerStopsWhenReactorStops(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
config := cfg.TestConfig()
const N = 2
_, switches := makeAndConnectReactors(config, N)
// stop reactors
for _, s := range switches {
assert.NoError(t, s.Stop())
}
// check that we are not leaking any go-routines
// i.e. broadcastTxRoutine finishes when reactor is stopped
leaktest.CheckTimeout(t, 10*time.Second)()
}
// mempoolLogger is a TestingLogger which uses a different
// color for each validator ("validator" key must exist).
func mempoolLogger() log.Logger {
return log.TestingLoggerWithColorFn(func(keyvals ...any) term.FgBgColor {
for i := 0; i < len(keyvals)-1; i += 2 {
if keyvals[i] == "validator" {
return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))}
}
}
return term.FgBgColor{}
})
}
// connect N mempool reactors through N switches
func makeAndConnectReactors(config *cfg.Config, n int) ([]*Reactor, []*p2p.Switch) {
reactors := make([]*Reactor, n)
logger := mempoolLogger()
for i := 0; i < n; i++ {
app := kvstore.NewInMemoryApplication()
cc := proxy.NewLocalClientCreator(app)
mempool, cleanup := newMempoolWithApp(cc)
defer cleanup()
reactors[i] = NewReactor(config.Mempool, mempool, false) // so we dont start the consensus states
reactors[i].SetLogger(logger.With("validator", i))
}
switches := p2p.MakeConnectedSwitches(config.P2P, n, func(i int, s *p2p.Switch) *p2p.Switch {
s.AddReactor("MEMPOOL", reactors[i])
return s
}, p2p.Connect2Switches)
return reactors, switches
}
func newUniqueTxs(n int) types.Txs {
txs := make(types.Txs, n)
for i := 0; i < n; i++ {
txs[i] = kvstore.NewTxFromID(i)
}
return txs
}
func waitForTxsOnReactors(t *testing.T, txs types.Txs, reactors []*Reactor) {
// wait for the txs in all mempools
wg := new(sync.WaitGroup)
for i, reactor := range reactors {
wg.Add(1)
go func(r *Reactor, reactorIndex int) {
defer wg.Done()
checkTxsInOrder(t, txs, r, reactorIndex)
}(reactor, i)
}
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
timer := time.After(timeout)
select {
case <-timer:
t.Fatal("Timed out waiting for txs")
case <-done:
}
}
// Wait until the mempool has a certain number of transactions.
func waitForNumTxsInMempool(numTxs int, mempool Mempool) {
for mempool.Size() < numTxs {
time.Sleep(time.Millisecond * 100)
}
}
// Wait until all txs are in the mempool and check that the number of txs in the
// mempool is as expected.
// func checkTxsInMempool(t *testing.T, txs types.Txs, reactor *Reactor, _ int) {
// t.Helper()
// waitForNumTxsInMempool(len(txs), reactor.mempool)
// reapedTxs := reactor.mempool.ReapMaxTxs(len(txs))
// require.Len(t, txs, len(reapedTxs))
// require.Len(t, txs, reactor.mempool.Size())
// }
// Wait until all txs are in the mempool and check that they are in the same
// order as given.
func checkTxsInOrder(t *testing.T, txs types.Txs, reactor *Reactor, reactorIndex int) {
waitForNumTxsInMempool(len(txs), reactor.mempool)
// Check that all transactions in the mempool are in the same order as txs.
reapedTxs := reactor.mempool.ReapMaxTxs(len(txs))
for i, tx := range txs {
assert.Equalf(t, tx, reapedTxs[i],
"txs at index %d on reactor %d don't match: %v vs %v", i, reactorIndex, tx, reapedTxs[i])
}
}
// ensure no txs on reactor after some timeout
func ensureNoTxs(t *testing.T, reactor *Reactor, timeout time.Duration) {
time.Sleep(timeout) // wait for the txs in all mempools
assert.Zero(t, reactor.mempool.Size())
}
func TestMempoolVectors(t *testing.T) {
testCases := []struct {
testName string
tx []byte
expBytes string
}{
{"tx 1", []byte{123}, "0a030a017b"},
{"tx 2", []byte("proto encoding in mempool"), "0a1b0a1970726f746f20656e636f64696e6720696e206d656d706f6f6c"},
}
for _, tc := range testCases {
msg := memproto.Message{
Sum: &memproto.Message_Txs{
Txs: &memproto.Txs{Txs: [][]byte{tc.tx}},
},
}
bz, err := msg.Marshal()
require.NoError(t, err, tc.testName)
require.Equal(t, tc.expBytes, hex.EncodeToString(bz), tc.testName)
}
}