forked from okx/xlayer-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_test.go
640 lines (579 loc) · 21.9 KB
/
server_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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
package jsonrpc
import (
"bytes"
"context"
"fmt"
"io"
"math/big"
"net/http"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/client"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/mocks"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/ethereum/go-ethereum/common"
ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/trie"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
const (
maxRequestsPerIPAndSecond = 1000
chainID uint64 = 1000
)
type mockedServer struct {
Config Config
Server *Server
ServerURL string
ServerWebSocketsURL string
}
type mocksWrapper struct {
Pool *mocks.PoolMock
State *mocks.StateMock
Etherman *mocks.EthermanMock
Storage *storageMock
DbTx *mocks.DBTxMock
}
func newMockedServer(t *testing.T, cfg Config) (*mockedServer, *mocksWrapper, *ethclient.Client) {
pool := mocks.NewPoolMock(t)
st := mocks.NewStateMock(t)
etherman := mocks.NewEthermanMock(t)
storage := newStorageMock(t)
dbTx := mocks.NewDBTxMock(t)
apis := map[string]bool{
APIEth: true,
APINet: true,
APIDebug: true,
APIZKEVM: true,
APITxPool: true,
APIWeb3: true,
}
var newL2BlockEventHandler state.NewL2BlockEventHandler = func(e state.NewL2BlockEvent) {}
st.On("RegisterNewL2BlockEventHandler", mock.IsType(newL2BlockEventHandler)).Once()
st.On("StartToMonitorNewL2Blocks").Once()
services := []Service{}
if _, ok := apis[APIEth]; ok {
services = append(services, Service{
Name: APIEth,
Service: NewEthEndpoints(cfg, chainID, pool, st, etherman, storage),
})
}
if _, ok := apis[APINet]; ok {
services = append(services, Service{
Name: APINet,
Service: NewNetEndpoints(cfg, chainID),
})
}
if _, ok := apis[APIZKEVM]; ok {
services = append(services, Service{
Name: APIZKEVM,
Service: NewZKEVMEndpoints(cfg, st, etherman),
})
}
if _, ok := apis[APITxPool]; ok {
services = append(services, Service{
Name: APITxPool,
Service: &TxPoolEndpoints{},
})
}
if _, ok := apis[APIDebug]; ok {
services = append(services, Service{
Name: APIDebug,
Service: NewDebugEndpoints(cfg, st, etherman),
})
}
if _, ok := apis[APIWeb3]; ok {
services = append(services, Service{
Name: APIWeb3,
Service: &Web3Endpoints{},
})
}
server := NewServer(cfg, chainID, pool, st, storage, services)
go func() {
err := server.Start()
if err != nil {
panic(err)
}
}()
serverURL := fmt.Sprintf("http://%s:%d", cfg.Host, cfg.Port)
for {
fmt.Println("waiting server to get ready...") // fmt is used here to avoid race condition with logs
res, err := http.Get(serverURL) //nolint:gosec
if err == nil && res.StatusCode == http.StatusOK {
fmt.Println("server ready!") // fmt is used here to avoid race condition with logs
break
}
time.Sleep(10 * time.Millisecond)
}
ethClient, err := ethclient.Dial(serverURL)
require.NoError(t, err)
serverWebSocketsURL := fmt.Sprintf("ws://%s:%d", cfg.WebSockets.Host, cfg.WebSockets.Port)
msv := &mockedServer{
Config: cfg,
Server: server,
ServerURL: serverURL,
ServerWebSocketsURL: serverWebSocketsURL,
}
mks := &mocksWrapper{
Pool: pool,
State: st,
Etherman: etherman,
Storage: storage,
DbTx: dbTx,
}
return msv, mks, ethClient
}
func getSequencerDefaultConfig() Config {
cfg := Config{
Host: "0.0.0.0",
Port: 9123,
MaxRequestsPerIPAndSecond: maxRequestsPerIPAndSecond,
MaxCumulativeGasUsed: 300000,
BatchRequestsEnabled: true,
MaxLogsCount: 10000,
MaxLogsBlockRange: 10000,
MaxNativeBlockHashBlockRange: 60000,
WebSockets: WebSocketsConfig{
Enabled: true,
Host: "0.0.0.0",
Port: 9133,
ReadLimit: 0,
},
}
return cfg
}
func getNonSequencerDefaultConfig(sequencerNodeURI string) Config {
cfg := getSequencerDefaultConfig()
cfg.Port = 9124
cfg.SequencerNodeURI = sequencerNodeURI
return cfg
}
func newSequencerMockedServer(t *testing.T) (*mockedServer, *mocksWrapper, *ethclient.Client) {
cfg := getSequencerDefaultConfig()
return newMockedServer(t, cfg)
}
func newMockedServerWithCustomConfig(t *testing.T, cfg Config) (*mockedServer, *mocksWrapper, *ethclient.Client) {
return newMockedServer(t, cfg)
}
func newNonSequencerMockedServer(t *testing.T, sequencerNodeURI string) (*mockedServer, *mocksWrapper, *ethclient.Client) {
cfg := getNonSequencerDefaultConfig(sequencerNodeURI)
return newMockedServer(t, cfg)
}
func (s *mockedServer) GetWSClient() *ethclient.Client {
ethClient, err := ethclient.Dial(s.ServerWebSocketsURL)
if err != nil {
panic(err)
}
return ethClient
}
func (s *mockedServer) Stop() {
err := s.Server.Stop()
if err != nil {
panic(err)
}
}
func (s *mockedServer) JSONRPCCall(method string, parameters ...interface{}) (types.Response, error) {
return client.JSONRPCCall(s.ServerURL, method, parameters...)
}
func (s *mockedServer) JSONRPCBatchCall(calls ...client.BatchCall) ([]types.Response, error) {
return client.JSONRPCBatchCall(s.ServerURL, calls...)
}
func (s *mockedServer) ChainID() uint64 {
return chainID
}
func TestBatchRequests(t *testing.T) {
type testCase struct {
Name string
BatchRequestsEnabled bool
BatchRequestsLimit uint
NumberOfRequests int
ExpectedError error
SetupMocks func(m *mocksWrapper, tc testCase)
}
block := state.NewL2Block(
state.NewL2Header(ðTypes.Header{Number: big.NewInt(2), UncleHash: ethTypes.EmptyUncleHash, Root: ethTypes.EmptyRootHash}),
[]*ethTypes.Transaction{ethTypes.NewTransaction(1, common.Address{}, big.NewInt(1), 1, big.NewInt(1), []byte{})},
nil,
[]*ethTypes.Receipt{ethTypes.NewReceipt([]byte{}, false, uint64(0))},
&trie.StackTrie{},
)
testCases := []testCase{
{
Name: "batch requests disabled",
BatchRequestsEnabled: false,
BatchRequestsLimit: 0,
NumberOfRequests: 10,
ExpectedError: fmt.Errorf("400 - " + types.ErrBatchRequestsDisabled.Error() + "\n"),
SetupMocks: func(m *mocksWrapper, tc testCase) {},
},
{
Name: "batch requests over the limit",
BatchRequestsEnabled: true,
BatchRequestsLimit: 5,
NumberOfRequests: 6,
ExpectedError: fmt.Errorf("413 - " + types.ErrBatchRequestsLimitExceeded.Error() + "\n"),
SetupMocks: func(m *mocksWrapper, tc testCase) {
},
},
{
Name: "batch requests unlimited",
BatchRequestsEnabled: true,
BatchRequestsLimit: 0,
NumberOfRequests: 100,
ExpectedError: nil,
SetupMocks: func(m *mocksWrapper, tc testCase) {
m.DbTx.On("Commit", context.Background()).Return(nil).Times(tc.NumberOfRequests)
m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Times(tc.NumberOfRequests)
m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(block.Number().Uint64(), nil).Times(tc.NumberOfRequests)
m.State.On("GetL2BlockByNumber", context.Background(), block.Number().Uint64(), m.DbTx).Return(block, nil).Times(tc.NumberOfRequests)
m.State.On("GetTransactionReceipt", context.Background(), mock.Anything, m.DbTx).Return(ethTypes.NewReceipt([]byte{}, false, uint64(0)), nil)
},
},
{
Name: "batch requests equal the limit",
BatchRequestsEnabled: true,
BatchRequestsLimit: 5,
NumberOfRequests: 5,
ExpectedError: nil,
SetupMocks: func(m *mocksWrapper, tc testCase) {
m.DbTx.On("Commit", context.Background()).Return(nil).Times(tc.NumberOfRequests)
m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Times(tc.NumberOfRequests)
m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(block.Number().Uint64(), nil).Times(tc.NumberOfRequests)
m.State.On("GetL2BlockByNumber", context.Background(), block.Number().Uint64(), m.DbTx).Return(block, nil).Times(tc.NumberOfRequests)
m.State.On("GetTransactionReceipt", context.Background(), mock.Anything, m.DbTx).Return(ethTypes.NewReceipt([]byte{}, false, uint64(0)), nil)
},
},
{
Name: "batch requests under the limit",
BatchRequestsEnabled: true,
BatchRequestsLimit: 5,
NumberOfRequests: 4,
ExpectedError: nil,
SetupMocks: func(m *mocksWrapper, tc testCase) {
m.DbTx.On("Commit", context.Background()).Return(nil).Times(tc.NumberOfRequests)
m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Times(tc.NumberOfRequests)
m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(block.Number().Uint64(), nil).Times(tc.NumberOfRequests)
m.State.On("GetL2BlockByNumber", context.Background(), block.Number().Uint64(), m.DbTx).Return(block, nil).Times(tc.NumberOfRequests)
m.State.On("GetTransactionReceipt", context.Background(), mock.Anything, m.DbTx).Return(ethTypes.NewReceipt([]byte{}, false, uint64(0)), nil)
},
},
}
for _, testCase := range testCases {
t.Run(testCase.Name, func(t *testing.T) {
tc := testCase
cfg := getSequencerDefaultConfig()
cfg.BatchRequestsEnabled = tc.BatchRequestsEnabled
cfg.BatchRequestsLimit = tc.BatchRequestsLimit
s, m, _ := newMockedServerWithCustomConfig(t, cfg)
tc.SetupMocks(m, tc)
calls := []client.BatchCall{}
for i := 0; i < tc.NumberOfRequests; i++ {
calls = append(calls, client.BatchCall{
Method: "eth_getBlockByNumber",
Parameters: []interface{}{"latest"},
})
}
result, err := s.JSONRPCBatchCall(calls...)
if testCase.ExpectedError == nil {
assert.Equal(t, testCase.NumberOfRequests, len(result))
} else {
assert.Equal(t, 0, len(result))
assert.Equal(t, testCase.ExpectedError.Error(), err.Error())
}
s.Stop()
})
}
}
func TestRequestValidation(t *testing.T) {
type testCase struct {
Name string
Method string
Content []byte
ContentType string
ExpectedStatusCode int
ExpectedResponseHeaders map[string][]string
ExpectedMessage string
}
testCases := []testCase{
{
Name: "OPTION request",
Method: http.MethodOptions,
ExpectedStatusCode: http.StatusOK,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"application/json"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "",
},
{
Name: "GET request",
Method: http.MethodGet,
ExpectedStatusCode: http.StatusOK,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"application/json"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "zkEVM JSON RPC Server",
},
{
Name: "HEAD request",
Method: http.MethodHead,
ExpectedStatusCode: http.StatusMethodNotAllowed,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "",
},
{
Name: "PUT request",
Method: http.MethodPut,
ExpectedStatusCode: http.StatusMethodNotAllowed,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "method PUT not allowed\n",
},
{
Name: "PATCH request",
Method: http.MethodPatch,
ExpectedStatusCode: http.StatusMethodNotAllowed,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "method PATCH not allowed\n",
},
{
Name: "DELETE request",
Method: http.MethodDelete,
ExpectedStatusCode: http.StatusMethodNotAllowed,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "method DELETE not allowed\n",
},
{
Name: "CONNECT request",
Method: http.MethodConnect,
ExpectedStatusCode: http.StatusNotFound,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
},
ExpectedMessage: "404 page not found\n",
},
{
Name: "TRACE request",
Method: http.MethodTrace,
ExpectedStatusCode: http.StatusMethodNotAllowed,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "method TRACE not allowed\n",
},
{
Name: "Request content bigger than limit",
Method: http.MethodPost,
Content: make([]byte, maxRequestContentLength+1),
ExpectedStatusCode: http.StatusRequestEntityTooLarge,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "content length too large (5242881>5242880)\n",
},
{
Name: "Invalid content type",
Method: http.MethodPost,
ContentType: "text/html",
ExpectedStatusCode: http.StatusUnsupportedMediaType,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "invalid content type, only application/json is supported\n",
},
{
Name: "Empty request body",
Method: http.MethodPost,
ContentType: contentType,
Content: []byte(""),
ExpectedStatusCode: http.StatusBadRequest,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "empty request body\n",
},
{
Name: "Invalid json",
Method: http.MethodPost,
ContentType: contentType,
Content: []byte("this is not a json format string"),
ExpectedStatusCode: http.StatusBadRequest,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "invalid json object request body\n",
},
{
Name: "Incomplete json object",
Method: http.MethodPost,
ContentType: contentType,
Content: []byte("{ \"field\":"),
ExpectedStatusCode: http.StatusBadRequest,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "invalid json object request body\n",
},
{
Name: "Incomplete json array",
Method: http.MethodPost,
ContentType: contentType,
Content: []byte("[ { \"field\":"),
ExpectedStatusCode: http.StatusBadRequest,
ExpectedResponseHeaders: map[string][]string{
"Content-Type": {"text/plain; charset=utf-8"},
"Access-Control-Allow-Origin": {"*"},
"Access-Control-Allow-Methods": {"POST, OPTIONS"},
"Access-Control-Allow-Headers": {"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"},
},
ExpectedMessage: "invalid json array request body\n",
},
}
s, _, _ := newSequencerMockedServer(t)
defer s.Stop()
for _, testCase := range testCases {
t.Run(testCase.Name, func(t *testing.T) {
tc := testCase
reqBodyReader := bytes.NewReader(tc.Content)
httpReq, err := http.NewRequest(tc.Method, s.ServerURL, reqBodyReader)
require.NoError(t, err)
httpReq.Header.Add("Content-type", tc.ContentType)
httpRes, err := http.DefaultClient.Do(httpReq)
require.NoError(t, err)
resBody, err := io.ReadAll(httpRes.Body)
require.NoError(t, err)
defer httpRes.Body.Close()
message := string(resBody)
assert.Equal(t, tc.ExpectedStatusCode, httpRes.StatusCode)
assert.Equal(t, tc.ExpectedMessage, message)
for responseHeaderKey, responseHeaderValue := range tc.ExpectedResponseHeaders {
assert.ElementsMatch(t, httpRes.Header[responseHeaderKey], responseHeaderValue)
}
})
}
}
func TestMaxRequestPerIPPerSec(t *testing.T) {
// this is the number of requests the test will execute
// it's important to keep this number with an amount of
// requests that the machine running this test is able
// to execute in a single second
const numberOfRequests = 100
// the number of workers are the amount of go routines
// the machine is able to run at the same time without
// consuming all the resources and making the go routines
// to affect each other performance, this number may vary
// depending on the machine spec running the test.
// a good number to this generally is a number close to
// the number of cores or threads provided by the CPU.
const workers = 12
// it's important to keep this limit smaller than the
// number of requests the test is going to perform, so
// the test can have some requests rejected.
const maxRequestsPerIPAndSecond = 20
cfg := getSequencerDefaultConfig()
cfg.MaxRequestsPerIPAndSecond = maxRequestsPerIPAndSecond
s, m, _ := newMockedServerWithCustomConfig(t, cfg)
defer s.Stop()
// since the limitation is made by second,
// the test waits 1 sec before starting because request are made during the
// server creation to check its availability. Waiting this second means
// we have a fresh second without any other request made.
time.Sleep(time.Second)
// create a wait group to wait for all the requests to return
wg := sync.WaitGroup{}
wg.Add(numberOfRequests)
// prepare mocks with specific amount of times it can be called
// this makes us sure the code is calling these methods only for
// allowed requests
times := int(cfg.MaxRequestsPerIPAndSecond)
m.DbTx.On("Commit", context.Background()).Return(nil).Times(times)
m.State.On("BeginStateTransaction", context.Background()).Return(m.DbTx, nil).Times(times)
m.State.On("GetLastL2BlockNumber", context.Background(), m.DbTx).Return(uint64(1), nil).Times(times)
// prepare the workers to process the requests as long as a job is available
requestsLimitedCount := uint64(0)
jobs := make(chan int, numberOfRequests)
// put each worker to work
for i := 0; i < workers; i++ {
// each worker works in a go routine to be able to have many
// workers working concurrently
go func() {
// a worker keeps working indefinitely looking for new jobs
for {
// waits until a job is available
<-jobs
// send the request
_, err := s.JSONRPCCall("eth_blockNumber")
// if the request works well or gets rejected due to max requests per sec, it's ok
// otherwise we stop the test and log the error.
if err != nil {
if err.Error() == "429 - You have reached maximum request limit." {
atomic.AddUint64(&requestsLimitedCount, 1)
} else {
require.NoError(t, err)
}
}
// registers in the wait group a request was executed and has returned
wg.Done()
}
}()
}
// add jobs to notify workers accordingly to the number
// of requests the test wants to send to the server
for i := 0; i < numberOfRequests; i++ {
jobs <- i
}
// wait for all the requests to return
wg.Wait()
// checks if all the exceeded requests were limited
assert.Equal(t, uint64(numberOfRequests-maxRequestsPerIPAndSecond), requestsLimitedCount)
// wait the server to process the last requests without breaking the
// connection abruptly
time.Sleep(time.Second)
}